(
cbOrTtl: number | ((input: any, opts: { path: string }) => number),
)
| 184 | }; |
| 185 | |
| 186 | export const cacheMiddleware = ( |
| 187 | cbOrTtl: number | ((input: any, opts: { path: string }) => number), |
| 188 | ) => |
| 189 | t.middleware(async ({ ctx, next, path, type, getRawInput, input }) => { |
| 190 | const ttl = |
| 191 | typeof cbOrTtl === 'function' ? cbOrTtl(input, { path }) : cbOrTtl; |
| 192 | if (!ttl) { |
| 193 | return next(); |
| 194 | } |
| 195 | const rawInput = await getRawInput(); |
| 196 | if (type !== 'query') { |
| 197 | return next(); |
| 198 | } |
| 199 | let key = `trpc:${path}:`; |
| 200 | if (rawInput) { |
| 201 | key += JSON.stringify(rawInput).replace(/\"/g, "'"); |
| 202 | } |
| 203 | const cache = await getRedisCache().getJson(key); |
| 204 | if (cache && process.env.NODE_ENV === 'production') { |
| 205 | return { |
| 206 | ok: true, |
| 207 | data: cache, |
| 208 | ctx, |
| 209 | marker: middlewareMarker, |
| 210 | }; |
| 211 | } |
| 212 | const result = await next(); |
| 213 | |
| 214 | // @ts-expect-error |
| 215 | if (result.data) { |
| 216 | getRedisCache().setJson( |
| 217 | key, |
| 218 | ttl, |
| 219 | // @ts-expect-error |
| 220 | result.data, |
| 221 | ); |
| 222 | } |
| 223 | return result; |
| 224 | }); |
no test coverage detected