perf(compose): Remove `await composed()` from hono.ts. (#495)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Taku Amano · committed by GitHub · parent 24a2894 · Browse files · 5 files·+140 added−102 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+140 added−102 removed
- tests:+82 added−80 removed
- other:+58 added−22 removed
Provenance
- Commit
f3087c9- Tree
3fa7844- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
24a2894
5 files changed+140 added−102 removed
modified:deno_dist/compose.ts+27 added-10 removed
123456789510111213141516171811192021222324252627282930213132233334353626272829303738394041424344454647484932505152import { HonoContext } from './context.ts'import type { NotFoundHandler } from './hono.ts'
interface ComposeContext { finalized: boolean res: any}
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <C>(middleware: Function[], onNotFound?: NotFoundHandler) => {export const compose = <C extends ComposeContext>( middleware: Function[], onNotFound?: NotFoundHandler) => { const middlewareLength = middleware.length return (context: C, next?: Function) => { let index = -1 return dispatch(0)
async function dispatch(i: number): Promise<C> { function dispatch(i: number): C | Promise<C> { if (i <= index) { throw new Error('next() called multiple times') } let handler = middleware[i] index = i if (i === middlewareLength && next) handler = next
let res
if (!handler) { if (context instanceof HonoContext && context.finalized === false && onNotFound) { context.res = await onNotFound(context) res = onNotFound(context) } return context } else { res = handler(context, async () => dispatch(i + 1)) }
const tmp = handler(context, () => dispatch(i + 1)) const res = tmp instanceof Promise ? await tmp : tmp
if (res && context instanceof HonoContext && context.finalized === false) { context.res = res if (!(res instanceof Promise)) { if (res && context.finalized === false) { context.res = res } return context } else { return res.then((res) => { if (res && context.finalized === false) { context.res = res } return context }) } return context } }}modified:deno_dist/hono.ts+2 added-1 removed
224 unmodified lines225 226 const composed = compose<HonoContext<string, E>>(handlers, this.notFoundHandler)227 let context: HonoContext<string, E>228 try {229- context = await composed(c)229+ const tmp = composed(c)230+ context = tmp instanceof Promise ? await tmp : tmp231 if (!context.finalized) {232 throw new Error(233 'Context is not finalized. You may forget returning Response object or `await next()`'234 )24 unmodified linesmodified:src/compose.test.ts+82 added-80 removed
6 unmodified lines7 8 type C = {9 req: Record<string, string>10 res: Record<string, string>11+ finalized: boolean12 }13 14+class ExpectedError extends Error {}15+16 describe('compose', () => {17 const middleware: Function[] = []18 19 const a = async (c: C, next: Function) => {23 unmodified lines43 middleware.push(c)44 middleware.push(handler)45 46 it('Request', async () => {44- const c: C = { req: {}, res: {} }47+ const c: C = { req: {}, res: {}, finalized: false }48 const composed = compose<C>(middleware)49 const context = await composed(c)50 expect(context.req['log']).not.toBeNull()51 expect(context.req['log']).toBe('log message')52 expect(context.req['xxx']).toBe('yyy')53 })54 it('Response', async () => {52- const c: C = { req: {}, res: {} }55+ const c: C = { req: {}, res: {}, finalized: false }56 const composed = compose<C>(middleware)57 const context = await composed(c)58 expect(context.res['headers']).not.toBeNull()59 expect(context.res['headers']).toBe('custom-header')3 unmodified lines63 })64 65 describe('compose with returning a promise, non-async funciton', () => {66 const handlers: Function[] = [64- (c: C) => {67+ () => {68 return new Promise((resolve) =>69 setTimeout(() => {67- c.res = { message: 'new response' }68- resolve(true)70+ resolve({ message: 'new response' })71 }, 1)72 )73 },74 ]75 76 it('Response', async () => {75- const c: C = { req: {}, res: {} }77+ const c: C = { req: {}, res: {}, finalized: false }78 const composed = compose<C>(handlers)79 const context = await composed(c)80 expect(context.res['message']).toBe('new response')81 })166 unmodified lines248 expect(context.finalized).toBe(true)249 })250 251 it('Run all the middlewares', async () => {250- const ctx: C = { req: {}, res: {} }252+ const ctx: C = { req: {}, res: {}, finalized: false }253 const stack: number[] = []254 const middlewares = [255 async (_ctx: C, next: Function) => {256 stack.push(0)82 unmodified lines339 await next()340 arr.push(4)341 })342 341- await compose(stack)({})343+ await compose(stack)({ res: null, finalized: false })344 expect(called).toEqual([true, true, true])345 expect(arr).toEqual([1, 2, 3, 4, 5, 6])346 })347 22 unmodified lines370 await next()371 arr.push(4)372 })373 372- await compose(stack)({})374+ await compose(stack)({ res: null, finalized: false })375 expect(called).toEqual([true, true])376 expect(arr).toEqual([1, 2, 6])377 })378 377- it('should be able to be called twice', () => {379+ it('should be able to be called twice', async () => {380 type C = {381 arr: number[]382 }383 const stack = []16 unmodified lines400 context.arr.push(4)401 })402 403 const fn = compose(stack)402- const ctx1 = { arr: [] as number[] }403- const ctx2 = { arr: [] as number[] }404+ const ctx1 = { arr: [] as number[], res: null, finalized: false }405+ const ctx2 = { arr: [] as number[], res: null, finalized: false }406 const out = [1, 2, 3, 4, 5, 6]407 406- return fn(ctx1)407- .then(() => {408- expect(out).toEqual(ctx1.arr)409- return fn(ctx2)410- })411- .then(() => {412- expect(out).toEqual(ctx2.arr)413- })408+ await fn(ctx1)409+410+ expect(out).toEqual(ctx1.arr)411+ await fn(ctx2)412+413+ expect(out).toEqual(ctx2.arr)414 })415 416- it('should create next functions that return a Promise', function () {416+ it('should create next functions that return a Promise', async () => {417 const stack: any[] = []418 const arr: any[] = []419 for (let i = 0; i < 5; i++) {420 stack.push((_context: C, next: Function) => {421 arr.push(next())422 })423 }424 425- compose(stack)({})425+ await compose(stack)({ res: null, finalized: false })426 427 for (const next of arr) {428 expect(isPromise(next)).toBe(true)429 }430 })431 432- it('should work with 0 middleware', function () {433- return compose([])({})432+ it('should work with 0 middleware', async () => {433+ await compose([])({ res: null, finalized: false })434 })435 436 it('should work when yielding at the end of the stack', async () => {437 const stack = []3 unmodified lines441 await next()442 called = true443 })444 445- await compose(stack)({})445+ await compose(stack)({ res: null, finalized: false })446 expect(called).toBe(true)447 })448 449- it('should reject on errors in middleware', () => {449+ it('should reject on errors in middleware', async () => {450 const stack = []451 452 stack.push(() => {453- throw new Error()453+ throw new ExpectedError()454 })455 456- return compose(stack)({}).then(457- () => {458- throw new Error('promise was not rejected')459- },460- (e) => {461- expect(e).toBeInstanceOf(Error)462- }463- )456+ try {457+ await compose(stack)({ res: null, finalized: false })458+ throw new Error('promise was not rejected')459+ } catch (e) {460+ expect(e).toBeInstanceOf(ExpectedError)461+ }462 })463 466- it('should keep the context', () => {467- const ctx = {}464+ it('should keep the context', async () => {465+ const ctx = { res: null, finalized: false }466 467 const stack = []468 469 stack.push(async (ctx2: C, next: Function) => {10 unmodified lines480 await next()481 expect(ctx2).toEqual(ctx)482 })483 486- return compose(stack)(ctx)484+ await compose(stack)(ctx)485 })486 487 it('should catch downstream errors', async () => {488 const arr: any[] = []15 unmodified lines504 arr.push(4)505 throw new Error()506 })507 510- await compose(stack)({})508+ await compose(stack)({ res: null, finalized: false })509 expect(arr).toEqual([1, 6, 4, 2, 3])510 })511 514- it('should compose w/ next', () => {512+ it('should compose w/ next', async () => {513 let called = false514 517- return compose([])({}, async () => {515+ await compose([])({ res: null, finalized: false }, async () => {516 called = true519- }).then(function () {520- expect(called).toBe(true)517 })518+ expect(called).toBe(true)519 })520 524- it('should handle errors in wrapped non-async functions', () => {521+ it('should handle errors in wrapped non-async functions', async () => {522 const stack = []523 524 stack.push(function () {528- throw new Error()525+ throw new ExpectedError()526 })527 531- return compose(stack)({}).then(532- () => {533- throw new Error('promise was not rejected')534- },535- (e) => {536- expect(e).toBeInstanceOf(Error)537- }538- )528+ try {529+ await compose(stack)({ res: null, finalized: false })530+ throw new Error('promise was not rejected')531+ } catch (e) {532+ expect(e).toBeInstanceOf(ExpectedError)533+ }534 })535 536 // https://github.com/koajs/compose/pull/27#issuecomment-143109739542- it('should compose w/ other compositions', () => {537+ it('should compose w/ other compositions', async () => {538 const called: number[] = []539 545- return compose([540+ await compose([541 compose([542 (_ctx: C, next: Function) => {543 called.push(1)544 return next()6 unmodified lines551 (_ctx: C, next: Function) => {552 called.push(3)553 return next()554 },560- ])({}).then(() => expect(called).toEqual([1, 2, 3]))555+ ])({ res: null, finalized: false })556+557+ expect(called).toEqual([1, 2, 3])558 })559 563- it('should throw if next() is called multiple times', () => {564- return compose([565- async (_ctx: C, next: Function) => {566- await next()567- await next()568- },569- ])({}).then(570- () => {571- throw new Error('boom')572- },573- (err) => {574- expect(/multiple times/.test(err.message)).toBe(true)575- }576- )560+ it('should throw if next() is called multiple times', async () => {561+ try {562+ await compose([563+ async (_ctx: C, next: Function) => {564+ await next()565+ await next()566+ },567+ ])({ res: null, finalized: false })568+ throw new Error('boom')569+ } catch (err) {570+ expect(err instanceof Error && /multiple times/.test(err.message)).toBe(true)571+ }572 })573 579- it('should return a valid middleware', () => {574+ it('should return a valid middleware', async () => {575 let val = 0581- return compose([576+ await compose([577 compose([578 (_ctx: C, next: Function) => {579 val++580 return next()6 unmodified lines587 (_ctx: C, next: Function) => {588 val++589 return next()590 },596- ])({}).then(function () {597- expect(val).toEqual(3)598- })591+ ])({ res: null, finalized: false })592+593+ expect(val).toEqual(3)594 })595 596 it('should return last return value', async () => {597 type C = {598 val: number599+ finalized: boolean600+ res: any601 }602 const stack = []603 604 stack.push(async (ctx: C, next: Function) => {7 unmodified lines612 await next()613 expect(ctx.val).toEqual(2)614 })615 619- const res = await compose(stack)({ val: 0 })620- expect(res).toEqual({ val: 1 })616+ const res = await compose<C>(stack)({ val: 0, res: null, finalized: false })617+ expect(res.val).toEqual(1)618 })619 620 it('should not affect the original middleware array', () => {621 const middleware = []16 unmodified lines638 it('should not get stuck on the passed in next', async () => {639 type C = {640 middleware: number641 next: number642+ finalized: boolean643+ res: any644 }645 646 const middleware = [647 (ctx: C, next: Function) => {3 unmodified lines651 ]652 const ctx = {653 middleware: 0,654 next: 0,655+ finalized: false,656+ res: null,657 }658 658- return compose(middleware)(ctx, (ctx: C, next: Function) => {659+ await compose<C>(middleware)(ctx, (ctx: C, next: Function) => {660 ctx.next++661 return next()661- }).then(() => {662- expect(ctx).toEqual({ middleware: 1, next: 1 })662 })663+664+ expect(ctx.middleware).toEqual(1)665+ expect(ctx.next).toEqual(1)666 })667 })modified:src/compose.ts+27 added-10 removed
123456789510111213141516171811192021222324252627282930213132233334353626272829303738394041424344454647484932505152import { HonoContext } from './context'import type { NotFoundHandler } from './hono'
interface ComposeContext { finalized: boolean res: any}
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <C>(middleware: Function[], onNotFound?: NotFoundHandler) => {export const compose = <C extends ComposeContext>( middleware: Function[], onNotFound?: NotFoundHandler) => { const middlewareLength = middleware.length return (context: C, next?: Function) => { let index = -1 return dispatch(0)
async function dispatch(i: number): Promise<C> { function dispatch(i: number): C | Promise<C> { if (i <= index) { throw new Error('next() called multiple times') } let handler = middleware[i] index = i if (i === middlewareLength && next) handler = next
let res
if (!handler) { if (context instanceof HonoContext && context.finalized === false && onNotFound) { context.res = await onNotFound(context) res = onNotFound(context) } return context } else { res = handler(context, async () => dispatch(i + 1)) }
const tmp = handler(context, () => dispatch(i + 1)) const res = tmp instanceof Promise ? await tmp : tmp
if (res && context instanceof HonoContext && context.finalized === false) { context.res = res if (!(res instanceof Promise)) { if (res && context.finalized === false) { context.res = res } return context } else { return res.then((res) => { if (res && context.finalized === false) { context.res = res } return context }) } return context } }}modified:src/hono.ts+2 added-1 removed
224 unmodified lines225 226 const composed = compose<HonoContext<string, E>>(handlers, this.notFoundHandler)227 let context: HonoContext<string, E>228 try {229- context = await composed(c)229+ const tmp = composed(c)230+ context = tmp instanceof Promise ? await tmp : tmp231 if (!context.finalized) {232 throw new Error(233 'Context is not finalized. You may forget returning Response object or `await next()`'234 )24 unmodified lines