Skip to content

Commit c045489

Browse files
fischi20atinux
andauthored
fix: UserSession type safety (#459)
Co-authored-by: Sébastien Chopin <seb@nuxt.com>
1 parent 1fbd99a commit c045489

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/runtime/server/utils/session.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { H3Event, SessionConfig } from 'h3'
22
import { useSession, createError, isEvent } from 'h3'
33
import { defu } from 'defu'
44
import { createHooks } from 'hookable'
5+
import type { OmitWithIndexSignature } from '../../types/utils'
56
import { useRuntimeConfig } from '#imports'
67
import type { UserSession, UserSessionRequired } from '#auth-utils'
78

@@ -40,7 +41,7 @@ export async function getUserSession(event: UseSessionEvent): Promise<UserSessio
4041
* @param data User session data, please only store public information since it can be decoded with API calls
4142
* @see https://github.com/atinux/nuxt-auth-utils
4243
*/
43-
export async function setUserSession(event: H3Event, data: Omit<UserSession, 'id'>, config?: Partial<SessionConfig>): Promise<UserSession> {
44+
export async function setUserSession(event: H3Event, data: OmitWithIndexSignature<UserSession, 'id'>, config?: Partial<SessionConfig>): Promise<UserSession> {
4445
const session = await _useSession(event, config)
4546

4647
await session.update(defu(data, session.data))
@@ -53,7 +54,7 @@ export async function setUserSession(event: H3Event, data: Omit<UserSession, 'id
5354
* @param event The Request (h3) event
5455
* @param data User session data, please only store public information since it can be decoded with API calls
5556
*/
56-
export async function replaceUserSession(event: H3Event, data: Omit<UserSession, 'id'>, config?: Partial<SessionConfig>): Promise<UserSession> {
57+
export async function replaceUserSession(event: H3Event, data: OmitWithIndexSignature<UserSession, 'id'>, config?: Partial<SessionConfig>): Promise<UserSession> {
5758
const session = await _useSession(event, config)
5859

5960
await session.clear()

src/runtime/types/utils.d.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
type Prettify<T> = {
2+
[K in keyof T]: T[K]
3+
}
4+
5+
type RemoveIndexSignature<T> = {
6+
[K in keyof T as string extends K ? never : K]: T[K]
7+
}
8+
9+
type GetIndexSignature<T> = {
10+
[K in keyof T as string extends K ? K : never]: T[K]
11+
}
12+
13+
// Basic Omit but does not break if a [x:string]:unknown Index Signature is present in the type
14+
export type OmitWithIndexSignature<T extends Record<string, unknown>, K extends keyof RemoveIndexSignature<T>> = Prettify<Omit<RemoveIndexSignature<T>, K> & GetIndexSignature<T>>

0 commit comments

Comments
 (0)