Repository navigation
|
Unless I'm missing something you can't have a middleware do pre/post style flow ala koa... .middleware(async ({ ctx, next }) => {
const auth = checkForAuth(ctx)
if (!auth) return handleUnauth(ctx)
await next()
const update = checkForUpdatedAuth(ctx)
if (update) {
ctx.res.headers['x-access-token'] = update.token
}
}) |
Replies: 7 comments 4 replies
|
You are correct. I actually considered calling middlewares something else when I made them as it is not the same as express middlewares. Originally it was called liked
|
|
Well in my exact situation I'm parsing a paseto token in the preNext, and in the postNext looking at the expiration date and if its within a bound using the refreshToken to regen the accessToken and send it back in headers. While you could do this outside of tRPC, you can't if you want to be protocol agnostic. You could do a pre/post hook, but as Koa has shown, just having async/await cleans thing up and keep stuff in logical places. |
|
I'd do both of those things in Doesn't seem like you need do that token regen after resolving the request, or am I misunderstanding? Secondly, createContext is called only once per request even if you're batching, but mutating as part of a middleware will be multiplied with the number of calls you did in that req and might produce some odd side effects. |
|
right now your encode/decode goes through transformer. but it could be a generic middleware if it was more like koa. also supporting things like brotli over the wire would just be another middleware. |
|
The goal wasn't really for tRPC to be completely standalone, but something you can plug in to whatever server you used. I first created the createHttpServer for the integration testing, exposing it was just a "meh, why not?" side-effect. Anyway, middlewares on a router level will not be the solution for your auth as they can be called several times in the same request (batching). Do this stuff in a connect middleware outside of tRPC or in your I won't change the current implementation - but I understand the naming is confusing, so open for suggestions on that. |
|
@KATT I have a couple more use cases for koa-style middleware, they simplest example being query time logging: .middleware(async ({ ctx, path, next }) => {
const start = Date.now()
await next()
const end = Date.now()
console.log({path, ctx, took: end - start})
})We also have some utils using There are other things that can be done like wrapping |
|
@KATT I also have a scenario where doing something past export const withCache = t.middleware(async ({ctx, next, path, rawInput, meta, type}) => {
// Cache only query procedures called with `createCaller` helper
const enableCache = type === "query" && isCreateCallerContext(ctx)
if (enableCache) {
const cached = cache.get({path, rawInput, meta})
if (cached) {
// Return cached data, if exists
// tRPC expects middleware to return an object with following properties
// Maybe this can be done using some sort of `overrideResult` helper function, which tRPC can take care of?
return {
ok: true, data: cached, marker: "middlewareMarker"
} as any
}
}
const result = await next({ctx: {...ctx, cache}})
if (result.ok === true && enableCache) {
cache.set({path, rawInput, meta}, (result as any).data)
}
return result
})Then, in // Notice that `getNote` is called twice in this file, so it fires 2 queries. That's where I need cache.
const getNote = createCaller((trpc, id: string) => trpc.note.getById({id}))
export async function generateMetadata({params}: Props): Promise<Metadata> {
const {title} = await getNote(params.id)
return {
title
}
}
const NoteViewPage: AFC<Props> = async ({params}) => {
const note = await getNote(params.id)
// ... component implementation ...
}
Also, I noticed that it does seem that output validation happens right after procedure returns its result. Am I right? Because I get an error when I return cached value, telling me that react can't serialize some of the result properties, if I don't manually serialize the result using same |
@KATT I have a couple more use cases for koa-style middleware, they simplest example being query time logging:
We also have some utils using
async_hookswhich would let us put things in AsyncLocalStorage and get them in the resolver this way. I don't think this is possible with the beforewares, but curious if you have any suggestions.There are other things that can be done like wrapping
await next()in a try/catch and doing error handling without needing special handlers.