patrick
patrick17mo ago

dynamic router creation

has anyone been able to create a dynamic router? e.g. i pass in the schema and some metadata and it produces the same routes but they are selected down to the metadata? my use case is i want to have crud against a set of tables... so i create a zod schema for each entity and want to create a router that does list, get, create, update, and delete, but for that one table, then i create one of each of these one per table... with what i've written, i'm getting the dreaded ts(2742) error.... The inferred type of 'routerForTable' cannot be named without a reference to '../../node_modules/@trpc/server/dist/core/parser.js'. This is likely not portable. A type annotation is necessary trying to pass in the schema as T extends z.ZodObject<z.ZodRawShape, z.UnknownKeysParam>
2 Replies
patrick
patrick17mo ago
export function getRouter<T extends z.ZodObject<z.ZodRawShape, z.UnknownKeysParam>>(tableName: string, schema: T) {
const client = getTableClient(tableName);
return router({
get: procedure
.input(z.string().uuid())
.output(schema)
.query(async ({ input: id }) => {
const result = await getRow(client, "", id);
return rowKeyToId<z.infer<typeof schema>>(result);
})
});
}
export function getRouter<T extends z.ZodObject<z.ZodRawShape, z.UnknownKeysParam>>(tableName: string, schema: T) {
const client = getTableClient(tableName);
return router({
get: procedure
.input(z.string().uuid())
.output(schema)
.query(async ({ input: id }) => {
const result = await getRow(client, "", id);
return rowKeyToId<z.infer<typeof schema>>(result);
})
});
}
Nick
Nick17mo ago
Yes I do this all the time Though I’m not sure what this error is, routerForTable doesn’t seem to be in this snippet? You probably need less generics/typing than you think though. Input/Output will handle the client types, and everything inside the factory just needs to be compatible with those