tRPCttRPC
Powered by
NeoBeanN
tRPC•3y ago•
3 replies
NeoBean

How to Type a Middleware factory?

Lemme first show you what I want, so you can get the gist of it. (Consider me less experienced in typescript)

publicProcedure
    .input(z.object({ test: z.boolean() }))
    .use(middlewareFactory( /** TO GET INPUT TYPECHECKING HERE */ ))
publicProcedure
    .input(z.object({ test: z.boolean() }))
    .use(middlewareFactory( /** TO GET INPUT TYPECHECKING HERE */ ))


This is what I put together. This almost works

/// types
type CustomPParams<T> = ProcedureParams<AnyRootConfig,unknown,unknown,T,unknown,unknown,unknown>
type MiddlewareFactory = <T>(input: T) => MiddlewareFunction<CustomPParams<T>, ProcedureParams>

/// a middleware factory
export const middlewareFactory: MiddlewareFactory = input => ({ next }) => { return next() }
/// types
type CustomPParams<T> = ProcedureParams<AnyRootConfig,unknown,unknown,T,unknown,unknown,unknown>
type MiddlewareFactory = <T>(input: T) => MiddlewareFunction<CustomPParams<T>, ProcedureParams>

/// a middleware factory
export const middlewareFactory: MiddlewareFactory = input => ({ next }) => { return next() }


I get autocompletion in vscode, but when I press tab and proceed with the autocompletion, I get an error that looks like this (the screenshot attached). Feels like i'm in the right path but cant exactly make a solid type out it.

Now, for my very specific use case, i did make an workaround by making that
T
T
generic partial
type MiddlewareFactory = <T>(input: Partial<T>) => MiddlewareFunction<CustomPParams<T>, ProcedureParams>
type MiddlewareFactory = <T>(input: Partial<T>) => MiddlewareFunction<CustomPParams<T>, ProcedureParams>


But this feels like a half measure. And provided that different validation libs might affect the type of input in subtle ways, I need to know how to properly type this thing.

Thank you
image.png
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

How to get the type of context after middleware context extension?
cha0sg0dCcha0sg0d / ❓-help
3y ago
how to access body in middleware
TaylorFayTTaylorFay / ❓-help
3y ago