DefinitelyTyped/types/koa-compose/koa-compose-tests.ts
Anton Astashov 4e4f50a2fc @types/koa-compose: Add more typed compose cases (#35298)
* @types/koa-compose: Add more typed compose cases

Right now if you want typesafe compose, you have to compose composes by
2-element arrays. I.e. if you have 4 middlewares you want to compose
together, and you want to do that in a typesafe way, without losing type
information, you have to do it like this:

```ts
import compose from "koa-compose"

const myMiddleware = compose([
  firstMiddleware,
  compose([
    secondMiddleware,
    compose([
      thirdMiddleware,
      fourthMiddleware
    ])
  ])
]);
```

It works, but looks clunky it complicated. Would be cool to still have
type-safe way of composing, but with less clunkiness. Like:

```
import compose from "koa-compose"

const myMiddleware = compose([
  firstMiddleware,
  secondMiddleware,
  thirdMiddleware,
  fourthMiddleware
]);
```

It's hard to solve that issue for general case, but we could just add
typesafe compose overrides for up to e.g. 8-element arrays. If it's more
than 8 - you still can compose composes. But in general IMHO it will
reduce clunkiness of it.

* @types/koa-compose: Add Anton Astashov to the list of maintainers
2019-05-22 09:13:50 -07:00

62 lines
1.4 KiB
TypeScript

import compose = require('koa-compose');
import * as Koa from "koa";
const fn1: compose.Middleware<any> = (context: any, next: () => Promise<void>): Promise<any> =>
Promise
.resolve(console.log('in fn1'))
.then(next);
const fn2: compose.Middleware<any> = (context: any, next: () => Promise<void>): Promise<any> =>
Promise
.resolve(console.log('in fn2'))
.then(next);
const fn = compose([fn1, fn2]);
interface FooCtx {
foo: string;
}
const fooMiddleware: Koa.Middleware<FooCtx> = async (ctx, next) => {
ctx.state.foo = "foo";
await next();
};
interface BarCtx {
bar: string;
}
const barMiddleware: Koa.Middleware<BarCtx> = async (ctx, next) => {
ctx.state.bar = "bar";
await next();
};
interface WooCtx {
woo: string;
}
const wooMiddleware: Koa.Middleware<WooCtx> = async (ctx, next) => {
ctx.state.woo = "woo";
await next();
};
new Koa<{}, {}>()
.use(compose([compose([fooMiddleware, barMiddleware]), wooMiddleware]))
.use(async (ctx, next) => {
ctx.state.foo;
ctx.state.bar;
ctx.state.woo;
ctx.body = "Something";
await next();
});
new Koa<{}, {}>()
.use(compose([fooMiddleware, barMiddleware, wooMiddleware]))
.use(async (ctx, next) => {
ctx.state.foo;
ctx.state.bar;
ctx.state.woo;
ctx.body = "Something";
await next();
});