-
I have this middleware:
TS says How do I set correct type for |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hello @bobgubko , I can offer you THREE options for doing that. Option 1: Making it awareCreate an EndpointsFactory equipped with the middleware that provides const customFactory = defaultEndpointsFactory.addMiddleware(
createMiddleware({
input: z.object({}),
middleware: async () => ({ em: { findOneOrFail: () => ({}) } }),
}),
);
export const anotherFactory = customFactory.addMiddleware(
createMiddleware({
input: z.object({
projectId: z.string().transform((value) => parseInt(value, 10)),
}),
middleware: async ({ options: { em } }) => {
const project = await em.findOneOrFail(); // em is known
return { project };
},
}),
); // here can go .build() if project is only needed for a single endpoint Option 2: Make is staticI'm not sure what const customFactory = defaultEndpointsFactory.addOptions({
em: { findOneOrFail: () => ({}) },
});
// continue same code as from the example above Moreover, if the chaining approach is not suitable, but import { em } from `src/db_handling`;
export const projectProviderMiddleware = createMiddleware({
input: z.object({
projectId: z.string().transform((value) => parseInt(value, 10)),
}),
middleware: async ({ input: { projectId } }) => {
const project = await em.findOneOrFail(Project, projectId)
return { project }
}
}) Option 3: Type narrowingIf none of the examples above seem suitable to you, you can check the presence and the type of export const projectProviderMiddleware = createMiddleware({
input: z.object({
projectId: z.string().transform((value) => parseInt(value, 10)),
}),
middleware: async ({ options, input: { projectId } }) => {
if (
"em" in options &&
typeof options.em === "object" &&
options.em !== null &&
"findOneOrFail" in options.em &&
typeof options.em.findOneOrFail === "function"
// or maybe: options.em instanceof DatabaseHandler
) {
const project = await options.em.findOneOrFail();
return { project }
}
return { project: null } // endpoint will have to verify that project !== null
}
}) If Moreover, you can simplify all those conditions using Zod schema: z.object({
em: z.object({
findOneOrFail: z.function()
})
}).safeParse(options)
// or
z.object({
em: z.instance() // in case em is an instance of some class
}).safeParse(options) Check out Zod's documentation on I assume that you're using version 14, which has changed I hope something of this will help you or at least give you an idea of the further direction. |
Beta Was this translation helpful? Give feedback.
Hello @bobgubko ,
I can offer you THREE options for doing that.
Option 1: Making it aware
Create an EndpointsFactory equipped with the middleware that provides
em
.Then,
addMiddleware
for creating another factory OR at the moment of creating an Endpoint (usingbuild
method).