entity-routes logo
Docs

Making a custom ContextAdapter#

So, you got a middleware-based Node layer that is neither Koa/Express and you want to be able to use entity-routes ? That can be done in 4 steps.

1. MiddlewareAdapter#

You need to make a MiddlewareAdapter and pass everything you want/need in your "context". Here is how Koa/Express middleware adapters are implemented :

#
typescript
1type AnyMiddlewareAdapter = (mw: Function) => (...args: any) => any;
3const expressMiddlewareAdapter = (mw: Function) => (req, res, next) => mw(makeExpressContextAdapter(req, res), next);
4const koaMiddleareAdapter = (mw: Function) => (ctx: Context, next: Next) => mw(makeKoaContextAdapter(ctx), next);

2. ContextAdapter factory#

Then you need to make the context adapter factory using the parameters you passed previously. Here is how context adapter factory are implemented for Koa/Express :

#
typescript
1export type KoaContextAdapter = ContextAdapter & { ctx: Context };
3export const makeKoaContextAdapter = (ctx: Context) =>
4 ({
5 ctx,
6 req: ctx.req,
7 res: ctx.res,
8 get method() {
9 return this.ctx.method;
10 },
11 get requestBody() {
12 return this.ctx.request.body;
13 },
14 get params() {
15 return this.ctx.params;
16 },
17 get query() {
18 return this.ctx.query;
19 },
20 get state() {
21 return this.ctx.state;
22 },
23 get responseBody() {
24 return this.ctx.body;
25 },
26 set responseBody(value) {
27 this.ctx.body = value;
28 },
29 get status() {
30 return this.ctx.status;
31 },
32 set status(value) {
33 this.ctx.status = value;
34 },
35 } as KoaContextAdapter);

3. routerRegisterFn#

You must define a routerRegisterFn, which register a BridgeRoute to a XXX route in XXX router, where XXX can be Koa/Express, etc.

#
typescript
1import { Middleware } from "koa";
2import * as Router from "koa-router";
4export function registerKoaRouteFromBridgeRoute(instance: Router, route: BridgeRouterRoute<Middleware>) {
5 instance.register(route.path, route.methods, route.middlewares, { name: route.name });
6}

4. makeXXXEntityRouters#

Finally, you can put these together and make your own makeXXXEntityRouters :

#
typescript
1export async function makeExpressEntityRouters(
2 args: Omit<MakeEntityRouters, "options"> & { options?: EntityRouteOptions }
3) {
4 return makeEntityRouters({
5 ...args,
6 options: {
7 ...args.options,
8 routerFactoryFn: Router,
9 routerRegisterFn: registerExpressRouteFromBridgeRoute,
10 middlewareAdapter: (mw: Function) => (req, res, next) => mw(makeExpressContextAdapter(req, res), next),
11 },
12 });
Prev
Koa