-
In my case I need to use same middleware on multiple nested routes. I've got custom middleware and routing as below: const contextProviderMiddleware = createMiddleware({
input: z.object({}),
middleware: async ({ response }) => ({
kCtx: response.locals.kCtx as Context,
}),
});
const routing: Routing = {
api: {
rest: {
v1: {
// user: new DependsOnMethod(userRoute),
product: {
"": new DependsOnMethod(productsRoute),
":id": {
"": new DependsOnMethod(productRoute),
relation: new DependsOnMethod(productsRoute),
},
},
category: new DependsOnMethod(categoriesRoute),
},
},
},
}; Currently I attach my middleware on every endpointFactory, what comes unconvenient and potentially risky to forget middleware appliance defaultEndpointsFactory
.addMiddleware(contextProvider) Is there any way to apply Like express way: app.use("/api/rest/v1/product", contextProviderGenerate(context as Context)); |
Beta Was this translation helpful? Give feedback.
Answered by
zdllucky
Feb 8, 2023
Replies: 1 comment
-
The answer is: you can configure and reuse same factory several times /// file1.ts
import contextProvider from "../middlewares/zod/contextProvider";
import { defaultResultHandler, EndpointsFactory } from "express-zod-api";
import { config } from "../index";
export const kCtxFactory = new EndpointsFactory({
resultHandler: defaultResultHandler,
config,
}).addMiddleware(contextProvider);
// or use defaultEndpointsFactory^ no difference
/// file2.ts
import { kCtxFactory } from "./file1";
export const get = kCtxFactory.build({/* ... */})
export const post = kCtxFactory.build({/* ... */})
export const patch = kCtxFactory.build({/* ... */}) Felt myself kinda dumb... The answer is very easy, still not intuitive from docs :) |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
zdllucky
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The answer is: you can configure and reuse same factory several times
Felt myself kinda dumb... The answer is very e…