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 fileTake it
feat: `app.onError` for handling error (#111)Yusuke Wadabefore adoption9de6328
line 1why, one step back1import { Context } from './context'feat: `app.notFound()` and `app.onError` (#117)Yusuke Wadabefore adoptionadb55ca
line 2why, one step back2import type { ErrorHandler } from './hono'feat: `app.onError` for handling error (#111)Yusuke Wadabefore adoption9de6328
line 3why, one step back3Migrate to TypeScript (#21)Yusuke Wadabefore adoptione6039f6
line 4why, one step back4// 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 back5export const compose = <T>(middleware: Function[], onError?: ErrorHandler) => {feat: check response type (#94)Yusuke Wadabefore adoptiond77d890
line 6why, one step back6 return function (context: T, next?: Function) {Migrate to TypeScript (#21)Yusuke Wadabefore adoptione6039f6
lines 7–8why, one step back7 let index = -18 return dispatch(0)refactor: compose (#116)Yusuke Wadabefore adoptiona66296b
line 9why, one step back9 async function dispatch(i: number): Promise<T> {Migrate to TypeScript (#21)Yusuke Wadabefore adoptione6039f6
lines 10–13why, one step back10 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 = nextrefactor: compose (#116)Yusuke Wadabefore adoptiona66296b
line 14why, one step back14 if (!fn) return contextMigrate to TypeScript (#21)Yusuke Wadabefore adoptione6039f6
line 15why, one step back15 try {refactor: compose (#116)Yusuke Wadabefore adoptiona66296b
lines 16–27why, one step back16 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 back28 } catch (err) {29 return Promise.reject(err)30 }31 }32 }33}