Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat✨: allow to change and persist cookie before nuxt init #229

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules\\typescript\\lib"
}
5 changes: 5 additions & 0 deletions packages/nuxt/playground/app.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script setup>
const local = useLocalUser()
const cookie = useCookieUser()
const preset_cookie = usePresetCookie()
</script>

<template>
Expand All @@ -12,4 +13,8 @@ const cookie = useCookieUser()
<span>Cookie:</span>
<input v-model="cookie.username">
</div>
<div>
<span>UserAgent:</span>
<input v-model="preset_cookie.token" readonly>
</div>
</template>
17 changes: 17 additions & 0 deletions packages/nuxt/playground/composables/presetCookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { defineStore } from 'pinia'

export const usePresetCookie = defineStore('preset-cookie', {
state: () => ({
access_token: 0,
refresh_token: 0,
}),
actions: {
setToken(token?: number) {
this.access_token = token ?? this.access_token + 1
this.refresh_token = token ?? this.refresh_token + 1
},
},
persist: {
storage: persistedState.cookies,
},
})
11 changes: 11 additions & 0 deletions packages/nuxt/playground/middleware/change-cookie.global.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* eslint-disable no-console */
/* eslint-disable n/prefer-global/process */
export default defineNuxtRouteMiddleware(() => {
if (process.client)
return
const preset_cookie = usePresetCookie()
console.log(toRaw(preset_cookie.$state))
preset_cookie.setToken()
console.log(toRaw(preset_cookie.$state))
persistCookie(preset_cookie, ['access_token'])
})
7 changes: 7 additions & 0 deletions packages/nuxt/src/constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const persisted_state = '__persisted-state'

declare module 'h3' {
interface H3EventContext {
[persisted_state]?: Record<string, any>
}
}
8 changes: 7 additions & 1 deletion packages/nuxt/src/module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addImports, addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'
import { addImports, addPlugin, addServerPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'
import { type CookieOptions } from 'nuxt/app'
import { type NuxtModule } from 'nuxt/schema'
import { defu } from 'defu'
Expand Down Expand Up @@ -36,9 +36,15 @@ export default defineNuxtModule<ModuleOptions>({
from: resolve('./runtime/storages'),
})

addImports({
name: 'persistCookie',
from: resolve('./runtime/persist-cookie'),
})

// provides plugin
nuxt.hook('modules:done', () => {
addPlugin(resolve('./runtime/plugin'), { append: true })
addServerPlugin(resolve('./server/plugin'))
})
},
}) satisfies NuxtModule<ModuleOptions>
12 changes: 12 additions & 0 deletions packages/nuxt/src/runtime/persist-cookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { Store } from 'pinia'
import { pick } from 'pinia-plugin-persistedstate'
import { persisted_state } from '../constant'
import { useRequestEvent } from '#imports'

export function persistCookie(store: Store, path?: string[]) {
const event = useRequestEvent()
if (event) {
const cookies = event.context[persisted_state] ??= {}
cookies[store.$id] = path ? pick(store.$state, path) : store.$state
}
}
11 changes: 11 additions & 0 deletions packages/nuxt/src/server/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { persisted_state } from '../constant'
import { defineNitroPlugin } from '#imports'

export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('render:response', (_, { event }) => {
const cookies = event.context[persisted_state] ?? {}
const id_list = Object.keys(cookies)
for (const id of id_list)
setCookie(event, id, JSON.stringify(cookies[id]))
})
})
4 changes: 4 additions & 0 deletions packages/nuxt/src/server/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "../../playground/.nuxt/tsconfig.server.json",
"include": ["./", "../runtime/persist-cookie.ts"]
}
3 changes: 2 additions & 1 deletion packages/nuxt/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"extends": "./playground/.nuxt/tsconfig.json",
"include": ["./src"]
"include": ["./src"],
"exclude": ["./src/server"]
}
2 changes: 2 additions & 0 deletions packages/plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { createPersistedState } from './plugin'

export { pick } from './pick'

export {
type PersistedStateOptions,
type PersistedStateFactoryOptions,
Expand Down
7 changes: 2 additions & 5 deletions packages/plugin/src/pick.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,10 @@ function get(state: StateTree, path: Array<string>): unknown {
}, state)
}

const ProtoRE = /^(__proto__)$/
function set(state: StateTree, path: Array<string>, val: unknown): StateTree {
return (
(path.slice(0, -1).reduce((obj, p) => {
if (/^(__proto__)$/.test(p))
return {}
else return (obj[p] = obj[p] || {})
}, state)[path[path.length - 1]] = val),
(path.slice(0, -1).reduce((obj, p) => ProtoRE.test(p) ? {} : (obj[p] ||= {}), state)[path.at(-1)!] = val),
state
)
}
Expand Down