koa-cache-control icon indicating copy to clipboard operation
koa-cache-control copied to clipboard

HOWTO: Custom Koa context in TypeScript with CacheControl params

Open matttowerssonos opened this issue 3 years ago • 0 comments

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

   ...
}

matttowerssonos avatar Jan 26 '22 01:01 matttowerssonos