Created
October 4, 2023 18:47
-
-
Save tyrauber/66a54ea4a62e6a9604995610d40e9a79 to your computer and use it in GitHub Desktop.
Koa / Express Shared Typescript Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Express, { Application, Request, Response, NextFunction } from 'express'; | |
import Koa, { Context, Next } from 'koa'; | |
const middleware = async (req: Request | Context['request'], res: Response | Context['response'], next: NextFunction) => { | |
console.log('Time:', Date.now()); | |
await next(); | |
} | |
interface Options {} | |
const Middleware = (app: Application | Koa, options:Options) => { | |
if (app instanceof Koa) { | |
app.use(async (ctx: Context, next: Next) => { | |
await middleware(ctx.request, ctx.response, next); | |
}); | |
} else { | |
app.use(async (req: Request, res: Response, next: NextFunction) => { | |
await middleware(req, res, next); | |
}); | |
} | |
}; | |
export default Middleware; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment