unjs / h3

⚡️ Minimal H(TTP) framework built for high performance and portability
https://h3.unjs.io/
MIT License
3.57k stars 210 forks source link

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

Closed remonke closed 2 months ago

remonke commented 3 months ago

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

pi0 commented 3 months ago

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

remonke commented 3 months ago

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.

pi0 commented 2 months ago

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