How do I add types to locals #158
-
Hi am trying to add PrismaCLient to request.locals through a global widdleware but I am failing to get the types when I am using in in the handlers I have tried this import { PrismaClient } from '@prisma/client'
import { Request, Response, MiddlewareNext, DefaultRequestLocals } from 'hyper-express/types'
const prisma = new PrismaClient()
interface Locals {
prisma: PrismaClient
}
export function GlobalPrismaMiddleware() {
return async (request: Request, response: Response, next: MiddlewareNext) => {
request.locals.prisma = prisma ?? new PrismaClient()
next()
}
} and // types.d.ts
/// <reference types="hyper-express/types" />
/// <reference types="@prisma/client" />
import { PrismaClient } from '@prisma/client'
declare global {
namespace 'hyper-express' {
interface Request {
prisma: PrismaClient
}
}
} what is the most efficient way to accomplish this |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Currently both type DefaultRequestLocals = {
[key: string]: any;
}; Due to this, the best you can do is extend the Another approach I have seen is where you define Request as an interface and then extend any custom properties inside of it. With this approach, you don't use locals (or I guess you can) and it would look something like this https://github.com/kartikk221/hyper-express-session/blob/3cd2918344b5f40638cb9c60377102dac89ed1df/types/index.d.ts#LL7-L10C6 |
Beta Was this translation helpful? Give feedback.
Currently both
Request
andResponse
locals have the following typeDue to this, the best you can do is extend the
DefaultRequestLocals
andDefaultResponseLocals
and then define your types inside of the extended type which then you can overload whenever you consumelocals
from either object.Another approach I have seen is where you define Request as an interface and then extend any custom properties inside of it. With this approach, you don't use locals (or I guess you can) and it would look something like this https://github.com/kartikk221/hyper-express-session/blob/3cd2918344b5f40638cb9c60377102dac89ed1df/types/index.d.ts#LL7-L10C6