drizzle-team / drizzle-trpc-zod

70 stars 3 forks source link

Demonstrate how to use a `createSelectSchema` output. #3

Open gburtini opened 2 months ago

gburtini commented 2 months ago

Hope this is reasonably useful as an issue, I realize its sort of of the shape "help me do the thing," but if I had figured out the intent clearly I would've just submitted a PR to add the guidance.

The documentation and example code shows how to use a createInsertSchema output

https://github.com/drizzle-team/drizzle-trpc-zod/blob/b2444e82f39496087094d11ee8867020c63c2a02/src/server.ts#L33-L35

But it only has the explicitly keyed where clause for the select side.

https://github.com/drizzle-team/drizzle-trpc-zod/blob/b2444e82f39496087094d11ee8867020c63c2a02/src/server.ts#L26-L32

drizzle-zod exposes a createSelectSchema

https://github.com/drizzle-team/drizzle-orm/blob/e0aaeb21b14f6027fc5a767d1f4617601650cb06/drizzle-zod/src/index.ts#L146-L158

But, I've struggled to figure out how it is intended to be used: an object which matches it can't directly be passed to a where clause, and strategies like looping over it seem fragile. Maybe this belongs better as feedback for drizzle-zod directly.

gburtini commented 2 months ago

For onlookers and in case it helps anyone else, this works for the purpose of deriving your API from your schema:

  users: t.procedure
    // apiSelectUser = createSelectSchema(...refinements)
    .input(apiSelectUser.partial())
    .query(({ input }) => {
      const keys = Object.keys(input);
      const where = and(
        ...keys.map((key) => {
          const value = input[key as keyof typeof input];
          const column = users[key as keyof typeof input];
          if (value === undefined) return undefined;
          return value !== null ? eq(column, value) : isNull(column);
        }),
      );

      return db.select().from(users).where(where);
    }),

...but it seems somewhat less elegant than the intent of createSelectSchema. I would be 0% surprised if I was missing something super obvious.