koa-cache-control
koa-cache-control copied to clipboard
HOWTO: Custom Koa context in TypeScript with CacheControl params
Add the types to your project
$ yarn add -D @types/koa-cache-control
Create a custom context that is composed of the legal options to pass to cacheControl(options?)
import * as cacheControl from 'koa-cache-control'
export interface RequestContext extends Koa.Context {
/**
* Cache Control
*/
readonly cacheControl: CacheControlParams
}
type CacheControlParams = Required<Parameters<typeof cacheControl>>[0]
Initialize the middleware:
const app: Koa<unknown, RequestContext> = new Koa()
app.get('ping', pingHandler)
async function pingHandler(ctx: RequestContext, next: Koa.Next): Promise<unknown> {
ctx.cacheControl.maxAge = 100 // typescript will provide syntax completion and type checking
...
}