Skip to content
Myr

compose.ts

This file

Path

src/compose.ts

33 lines · 1.0 KiB · TypeScript

Last changed by

feat: `app.notFound()` and `app.onError` (#117)Yusuke Wadabefore adoptionadb55ca

History of this file

Take it

feat: `app.onError` for handling error (#111)Yusuke Wadabefore adoption9de6328

line 1why, one step back
1import { Context } from './context'

feat: `app.notFound()` and `app.onError` (#117)Yusuke Wadabefore adoptionadb55ca

line 2why, one step back
2import type { ErrorHandler } from './hono'

feat: `app.onError` for handling error (#111)Yusuke Wadabefore adoption9de6328

line 3why, one step back
3

Migrate to TypeScript (#21)Yusuke Wadabefore adoptione6039f6

line 4why, one step back
4// Based on the code in the MIT licensed `koa-compose` package.

feat: `app.notFound()` and `app.onError` (#117)Yusuke Wadabefore adoptionadb55ca

line 5why, one step back
5export const compose = <T>(middleware: Function[], onError?: ErrorHandler) => {

feat: check response type (#94)Yusuke Wadabefore adoptiond77d890

line 6why, one step back
6 return function (context: T, next?: Function) {

Migrate to TypeScript (#21)Yusuke Wadabefore adoptione6039f6

lines 7–8why, one step back
7 let index = -1
8 return dispatch(0)

refactor: compose (#116)Yusuke Wadabefore adoptiona66296b

line 9why, one step back
9 async function dispatch(i: number): Promise<T> {

Migrate to TypeScript (#21)Yusuke Wadabefore adoptione6039f6

lines 10–13why, one step back
10 if (i <= index) return Promise.reject(new Error('next() called multiple times'))
11 index = i12 let fn = middleware[i]13 if (i === middleware.length) fn = next

refactor: compose (#116)Yusuke Wadabefore adoptiona66296b

line 14why, one step back
14 if (!fn) return context

Migrate to TypeScript (#21)Yusuke Wadabefore adoptione6039f6

line 15why, one step back
15 try {

refactor: compose (#116)Yusuke Wadabefore adoptiona66296b

lines 16–27why, one step back
16 return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
17 .then(() => {18 return context19 })20 .catch((err) => {21 if (onError && context instanceof Context) {22 context.res = onError(err, context)23 return context24 } else {25 throw err26 }27 })

Migrate to TypeScript (#21)Yusuke Wadabefore adoptione6039f6

lines 28–33why, one step back
28 } catch (err) {
29 return Promise.reject(err)30 }31 }32 }33}