Skip to content

Commit e74f238

Browse files
feat: add replaceUserSession() (#44)
* feat: add replaceUserSession() * chore: update --------- Co-authored-by: Sébastien Chopin <[email protected]>
1 parent e761369 commit e74f238

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ The following helpers are auto-imported in your `server/` directory.
9090
```ts
9191
// Set a user session, note that this data is encrypted in the cookie but can be decrypted with an API call
9292
// Only store the data that allow you to recognize an user, but do not store sensitive data
93+
// Merges new data with existing data using defu()
9394
await setUserSession(event, {
9495
user: {
9596
// ... user data
@@ -98,6 +99,9 @@ await setUserSession(event, {
9899
// Any extra fields
99100
})
100101

102+
// Replace a user session. Same behaviour as setUserSession, except it does not merge data with existing data
103+
await replaceUserSession(event, data)
104+
101105
// Get the current user session
102106
const session = await getUserSession(event)
103107

src/module.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ export default defineNuxtModule<ModuleOptions>({
4242
'sessionHooks',
4343
'getUserSession',
4444
'setUserSession',
45+
'replaceUserSession',
4546
'clearUserSession',
4647
'requireUserSession',
4748
]

src/runtime/server/utils/session.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,20 @@ export async function setUserSession (event: H3Event, data: UserSession) {
3636
return session.data
3737
}
3838

39+
/**
40+
* Replace a user session
41+
* @param event
42+
* @param data User session data, please only store public information since it can be decoded with API calls
43+
*/
44+
export async function replaceUserSession (event: H3Event, data: UserSession) {
45+
const session = await _useSession(event)
46+
47+
await session.clear()
48+
await session.update(data)
49+
50+
return session.data
51+
}
52+
3953
export async function clearUserSession (event: H3Event) {
4054
const session = await _useSession(event)
4155

0 commit comments

Comments
 (0)