Skip to main content

Extending with Middlewares

Whereas HttpServerShim provides many default request pre and post handlers, you may want to add your own custom middleware to control body-parsing or header-parsing behavior in a globel level. Such server-wide middleware support is provided by HttpServerShim.addMiddleware(handler).

export class MyAppServer extends HttpServerShim {
...
}

server.addMiddleware(async (op) => {
op.oriReq // you can access original request object from Express of Fastify
op.oriRes // you can access original response object from Express of Fastify

// no need for `next()` as `op` object will be passed to APIs
})

Custom pre and post Handlers

In HttpServerShim terms, pre handler runs during request reception, and post handler runs after op object returns. You can individually override the pre and post behavior of a standalone httpOp by providing callbacks config at the op definition

import { HttpServerShim, httpOp, httpParam, httpReturn, required } from 'ts-basis/nodejs'

export class MyAppServer extends HttpServerShim {
...
async initialize() {
...
// Preprocessors (e.g. JSON body-parsing)
this.addDefaultProcessor(
ReqProcessor.AUTH, // checks token in Authorization header if custom handler is not defined
ReqProcessor.BASIC, // auto-parses body to JSON; much like json-parse middleware
)
}
}

server.addMiddleware(async (op) => {
...
})

// Define standalone server operation with well-known input/output
export const myApiFunction = httpOp(
{
params: {},
callbacks: {
onBeforePre: (op) => {
// runs before pre-processing
},
onAfterPre: (op) => {
// runs after pre-processing
},
onBeforePost: (op) => {
// runs before post-processing
},
onAfterPost: (op) => {
// runs after post-processing
},
},
returns: httpReturn<{ data: string }>(),
},
async (op) => {
return op.returnJson({ data: 'Hello World!' })

// ==== Order of Processing ====
//
// custom middlewares (addMiddleware)
// onBeforePre
// ReqProcessor.AUTH
// ReqProcessor.BASIC (json parser)
// onAfterPre
// this function: async (op) => {
// return op.returnJson({ data: 'Hello World!' })
// }
// onBeforePost
// Post-processing
// onAfterPost
//
},
)