h3 icon indicating copy to clipboard operation
h3 copied to clipboard

Improve type safety in `useSession` by using `Partial` for `SessionData`

Open remonke opened this issue 1 year ago • 2 comments

Describe the feature

The current API lacks type safety because the session defaults to an empty object, which is not properly handled in the implementation. To improve type safety, I recommend the following change:

export type SessionData<T extends SessionDataT = SessionDataT> = Partial<T>;

Additional information

  • [X] Would you be willing to help implement this feature?

remonke avatar Jun 18 '24 12:06 remonke

Can you please elaborate more in which cases it can be beneficial? (a code repo example would be nice)

pi0 avatar Jun 19 '24 13:06 pi0

Here's the most obvious example I can think of:

type SessionData = {
  userId: string;
};

export default eventHandler(async (event) => {
  const session = await useSession<SessionData>(event, {
    ...
  });

  const { title } = await readBody(event);

  const todo = await useDrizzle()
    .insert(tables.todos)
    .values({
      title,
      userId: session.data.userId,
      createdAt: new Date(),
    })
    .returning()
    .get();


  return todo;
});

Sure, I know this code won't work right if a user isn't authenticated. But another person working on my code might not know this, and TypeScript won't give an error. If I saw code like this not erroring, I would just think useSession throws an error for a non authenticated user.

I'm fine with the session having a generic type, but if I ever need to use unsafe code, I'll just use as myself.

ghost avatar Jun 19 '24 16:06 ghost

Thanks for explaining. Types will be partial in h3 v2.

pi0 avatar Jul 18 '24 22:07 pi0