A simple implements for interceptor in JavaScript/TypeScript.
- TypeScript v5 (or newer)
- Node.js v16 (or newer)
npm i @litert/interceptor --save
import { InterceptorChain } from "@litert/interceptor";
const chain = new InterceptorChain<IApiRequest, IApiResponse>([
async function(ctx, next) { // logger
const STARTED = Date.now();
try {
await next();
console.log(`[INFO] ${ctx.input.method} ${ctx.input.url} ${Date.now() - STARTED}ms`);
}
catch (e) {
console.error(`[ERROR] ${ctx.input.method} ${ctx.input.url} ${Date.now() - STARTED}ms`);
console.error(e);
}
},
async function(ctx) { // auth
await authMgr.authenticate(ctx.input);
},
async function(ctx, next) { // rate limit
await rateLimitMgr.check(ctx.input);
},
async function(ctx) { // dispatcher
ctx.result = await apiDispatcher.dispatch(ctx.input);
}
]);
const result = await chain.execute(apiReq);
See more in examples.
This library is published under Apache-2.0 license.