Skip to content

Instantly share code, notes, and snippets.

@ngot
Created May 24, 2020 13:56
Show Gist options
  • Save ngot/8c5ffd95bb400811db0bf76b1d0c630f to your computer and use it in GitHub Desktop.
Save ngot/8c5ffd95bb400811db0bf76b1d0c630f to your computer and use it in GitHub Desktop.
A simple demo of Koa in TypeScript
import Session from "koa-session";
import Router from "koa-router";
import Koa from "koa";
interface IContext {
dummy: string;
}
interface JContext {
dummy: number;
}
type RContext = Koa.ParameterizedContext<
Koa.DefaultState,
Router.IRouterParamContext<Koa.DefaultState, Koa.Context>
& Koa.Context
& IContext | JContext
>;
// Must pass the generic
const app = new Koa<Koa.DefaultState, RContext>();
// Must pass the generic
const router = new Router<Koa.DefaultState, RContext>();
// Must have type
function yumy(ctx: RContext, next: Koa.Next) {
ctx.dummy = "dummy 1";
ctx.dummy = 123;
return next();
}
app.use(yumy);
// No need type
app.use((ctx, next: Koa.Next) => {
console.log(ctx.dummy);
ctx.dummy = "dummy 2";
ctx.dummy = 456;
return next();
});
// Must have type
function ctrl(ctx: RContext) {
ctx.body = ctx.dummy;
}
router.get("/dummy/:id", ctrl);
app.use(router.routes());
app.listen(4000, () => {
console.log('4000...');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment