Skip to content
Myr

refactor(types): reduce type definitions (#649)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* refactor(types): reduce type definitions * fixed tests for Deno and Bun

authored by Yusuke Wada · committed by GitHub · parent 8e9b1c8 · Browse files · 13 files+78 added−185 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+78 added−185 removed

  • tests:+20 added−23 removed
  • other:+58 added−162 removed

13 files+78 added−185 removed

modified:bun_test/index.test.tsx+2 added-2 removed
modified:deno_dist/compose.ts+7 added-13 removed
1import { HonoContext } from './context.ts'1import { Context } from './context.ts'2import type { Environment, NotFoundHandler, ErrorHandler } from './types.ts'3import type { Schema } from './validator/schema.ts'34interface ComposeContext {5 finalized: boolean6 res: unknown7}89// Based on the code in the MIT licensed `koa-compose` package.11export const compose = <12 C extends ComposeContext,13 P extends string = string,14 E extends Partial<Environment> = Environment,15 D extends Partial<Schema> = Schema16>(10export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>(11 middleware: Function[],18 onNotFound?: NotFoundHandler<P, E, D>,19 onError?: ErrorHandler<P, E, D>12 onNotFound?: NotFoundHandler<E>,13 onError?: ErrorHandler<E>14) => {15 const middlewareLength = middleware.length16 return (context: C, next?: Function) => {17 let index = -1
10 unmodified lines
28 let res29 let isError = false3031 if (!handler) {38 if (context instanceof HonoContext && context.finalized === false && onNotFound) {32 if (context instanceof Context && context.finalized === false && onNotFound) {33 res = onNotFound(context)34 }35 } else {36 try {
1 unmodified line
38 const dispatchRes = dispatch(i + 1)39 return dispatchRes instanceof Promise ? dispatchRes : Promise.resolve(dispatchRes)40 })41 } catch (err) {48 if (err instanceof Error && context instanceof HonoContext && onError) {42 if (err instanceof Error && context instanceof Context && onError) {43 context.error = err44 res = onError(err, context)45 isError = true46 } else {
15 unmodified lines
62 }63 return context64 })65 .catch((err) => {72 if (err instanceof Error && context instanceof HonoContext && onError) {66 if (err instanceof Error && context instanceof Context && onError) {67 context.error = err68 context.res = onError(err, context)69 return context70 }
6 unmodified lines
modified:deno_dist/context.ts+4 added-43 removed
7 unmodified lines
8type Headers = Record<string, string | string[]>9type Runtime = 'node' | 'deno' | 'bun' | 'cloudflare' | 'fastly' | 'vercel' | 'other'10export type Data = string | ArrayBuffer | ReadableStream1112export interface Context<12export class Context<13 P extends string = string,14 E extends Partial<Environment> = Environment,15 S extends Partial<Schema> | unknown = Schema16> {17 req: Request<P, S extends Schema ? SchemaToProp<S> : any>18 env: E['Bindings']19 event: FetchEvent20 executionCtx: ExecutionContext19 finalized: boolean22 error: Error | undefined2324 get res(): Response25 set res(_res: Response)26 header: (name: string, value: string, options?: { append?: boolean }) => void27 status: (status: StatusCode) => void28 set: {29 <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void30 <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void31 (key: string, value: unknown): void32 }33 get: {34 <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]35 <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]36 <T = any>(key: string): T37 }38 pretty: (prettyJSON: boolean, space?: number) => void39 newResponse: (data: Data | null, status: StatusCode, headers: Headers) => Response40 body: (data: Data | null, status?: StatusCode, headers?: Headers) => Response41 text: (text: string, status?: StatusCode, headers?: Headers) => Response42 json: <T>(object: T, status?: StatusCode, headers?: Headers) => Response43 html: (html: string, status?: StatusCode, headers?: Headers) => Response44 redirect: (location: string, status?: StatusCode) => Response45 cookie: (name: string, value: string, options?: CookieOptions) => void46 notFound: () => Response | Promise<Response>47 get runtime(): Runtime48}4950export class HonoContext<51 P extends string = string,52 E extends Partial<Environment> = Environment,53 S extends Partial<Schema> = Schema54> implements Context<P, E, S>55{56 req: Request<P, S extends Schema ? SchemaToProp<S> : any>57 env: E['Bindings']58 finalized: boolean20 error: Error | undefined = undefined2122 _status: StatusCode = 20023 private _executionCtx: FetchEvent | ExecutionContext | undefined
1 unmodified line
25 private _prettySpace: number = 226 private _map: Record<string, unknown> | undefined27 private _headers: Record<string, string[]> | undefined28 private _res: Response | undefined68 private notFoundHandler: NotFoundHandler<P, E, S>29 private notFoundHandler: NotFoundHandler<E>3031 constructor(32 req: Request<P>,33 env: E['Bindings'] = {},34 executionCtx: FetchEvent | ExecutionContext | undefined = undefined,74 notFoundHandler: NotFoundHandler<P, E, S> = () => new Response()35 notFoundHandler: NotFoundHandler<E> = () => new Response()36 ) {37 this._executionCtx = executionCtx38 this.req = req as Request<P, S extends Schema ? SchemaToProp<S> : any>39 this.env = env || ({} as Bindings)
150 unmodified lines
190 this.header('set-cookie', cookie, { append: true })191 }192193 notFound(): Response | Promise<Response> {233 return this.notFoundHandler(this)194 return this.notFoundHandler(this as unknown as Context<string, E>)195 }196197 get runtime(): Runtime {198 // eslint-disable-next-line @typescript-eslint/no-explicit-any
29 unmodified lines
modified:deno_dist/hono.ts+11 added-15 removed
1import { compose } from './compose.ts'2import type { Context } from './context.ts'3import { HonoContext } from './context.ts'2import { Context } from './context.ts'3import { extendRequestPrototype } from './request.ts'4import type { Router } from './router.ts'5import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router.ts'6import { RegExpRouter } from './router/reg-exp-router/index.ts'
91 unmodified lines
9899 Object.assign(this, init)100 }101103 private notFoundHandler: NotFoundHandler<P, E, S> = (c: Context<P, E, S>) => {102 private notFoundHandler: NotFoundHandler<E> = (c: Context<string, E>) => {103 return c.text('404 Not Found', 404)104 }105107 private errorHandler: ErrorHandler<P, E, S> = (err: Error, c: Context<P, E, S>) => {106 private errorHandler: ErrorHandler<E> = (err: Error, c: Context<string, E>) => {107 console.trace(err.message)108 const message = 'Internal Server Error'109 return c.text(message, 500)110 }111112 // eslint-disable-next-line @typescript-eslint/no-explicit-any113 route(path: string, app?: Hono<E, P, S>) {113 route(path: string, app?: Hono<any>) {114 this._tempPath = path115 if (app) {116 app.routes.map((r) => {117 this.addRoute(r.method, r.path, r.handler)117 this.addRoute(r.method, r.path, r.handler as unknown as Handler<P, E>)118 })119 this._tempPath = ''120 }121 return this
17 unmodified lines
139 })140 return this141 }142143 onError(handler: ErrorHandler<P, E, S>) {143 onError(handler: ErrorHandler<E>) {144 this.errorHandler = handler145 return this146 }147148 notFound(handler: NotFoundHandler<P, E, S>) {148 notFound(handler: NotFoundHandler<E>) {149 this.notFoundHandler = handler150 return this151 }152
10 unmodified lines
163 private matchRoute(method: string, path: string) {164 return this.router.match(method, path)165 }166167 private handleError(err: unknown, c: Context<P, E, S>) {167 private handleError(err: unknown, c: Context<string, E, S>) {168 if (err instanceof Error) {169 return this.errorHandler(err, c)170 }171 throw err
9 unmodified lines
181182 const result = this.matchRoute(method, path)183 request.paramData = result?.params184185 const c = new HonoContext<P, E, S>(request, env, eventOrExecutionCtx, this.notFoundHandler)185 const c = new Context<string, E, S>(request, env, eventOrExecutionCtx, this.notFoundHandler)186187 // Do not `compose` if it has only one handler188 if (result && result.handlers.length === 1) {189 const handler = result.handlers[0]
22 unmodified lines
212 })()213 }214215 const handlers = result ? result.handlers : [this.notFoundHandler]216 const composed = compose<HonoContext<P, E, S>, P, E, S>(217 handlers,218 this.notFoundHandler,219 this.errorHandler220 )216 const composed = compose<Context<P, E, S>, E>(handlers, this.notFoundHandler, this.errorHandler)217218 return (async () => {219 try {220 const tmp = composed(c)
26 unmodified lines
modified:deno_dist/types.ts+7 added-10 removed
20 unmodified lines
21 E extends Partial<Environment> = Environment,22 S extends Partial<Schema> = Schema23> = (c: Context<P, E, S>, next: Next) => Promise<Response | undefined | void>2425export type NotFoundHandler<26 P extends string = string,27 E extends Partial<Environment> = Environment,28 S extends Partial<Schema> = Schema29> = (c: Context<P, E, S>) => Response | Promise<Response>25export type NotFoundHandler<E extends Partial<Environment> = Environment> = (26 c: Context<string, E>27) => Response | Promise<Response>2831export type ErrorHandler<32 P extends string = string,33 E extends Partial<Environment> = Environment,34 S extends Partial<Schema> = Schema35> = (err: Error, c: Context<P, E, S>) => Response29export type ErrorHandler<E extends Partial<Environment> = Environment> = (30 err: Error,31 c: Context<string, E>32) => Response3334export type Next = () => Promise<void>3536// eslint-disable-next-line @typescript-eslint/no-unused-vars
54 unmodified lines
modified:deno_test/hono.test.ts+2 added-3 removed
modified:src/validator/validator.test.ts-1 removed
59 unmodified lines
6061 it('Should be invalid - ids', async () => {62 const validator = v.queries('ids').isRequired()63 const results = await validator.validate(req)64 console.log(results)64 expect(results[0].isValid).toBe(true)65 expect(results[1].isValid).toBe(false)66 expect(results[1].message).toBe(67 'Invalid Value []: the query parameters "ids" is invalid - isRequired'
750 unmodified lines
modified:src/compose.test.ts+8 added-9 removed
1import { compose } from './compose'2import type { Context } from './context'3import { HonoContext } from './context'2import { Context } from './context'3import { extendRequestPrototype } from './request'45extendRequestPrototype()6
76 unmodified lines
83describe('Handler and middlewares', () => {84 const middleware: Function[] = []8586 const req = new Request('http://localhost/')88 const c: Context = new HonoContext(req)87 const c: Context = new Context(req)8889 const mHandlerFoo = async (c: Context, next: Function) => {90 c.req.headers.append('x-header-foo', 'foo')91 await next()
27 unmodified lines
119describe('compose with Context - 200 success', () => {120 const middleware: Function[] = []121122 const req = new Request('http://localhost/')124 const c: Context = new HonoContext(req)123 const c: Context = new Context(req)124 const handler = (c: Context) => {125 return c.text('Hello')126 }127 const mHandler = async (_c: Context, next: Function) => {
15 unmodified lines
143describe('compose with Context - 404 not found', () => {144 const middleware: Function[] = []145146 const req = new Request('http://localhost/')148 const c: Context = new HonoContext(req)147 const c: Context = new Context(req)148 const onNotFound = (c: Context) => {149 return c.text('onNotFound', 404)150 }151 const mHandler = async (_c: Context, next: Function) => {
15 unmodified lines
167describe('compose with Context - 401 not authorized', () => {168 const middleware: Function[] = []169170 const req = new Request('http://localhost/')172 const c: Context = new HonoContext(req)171 const c: Context = new Context(req)172 const handler = (c: Context, _next: Function) => {173 return c.text('Hello')174 }175 const mHandler = async (c: Context, next: Function) => {
17 unmodified lines
193describe('compose with Context - next() below', () => {194 const middleware: Function[] = []195196 const req = new Request('http://localhost/')198 const c: Context = new HonoContext(req)197 const c: Context = new Context(req)198 const handler = (c: Context) => {199 const message = c.req.header('x-custom') || 'blank'200 return c.text(message)201 }
18 unmodified lines
220describe('compose with Context - 500 error', () => {221 const middleware: Function[] = []222223 const req = new Request('http://localhost/')225 const c: Context = new HonoContext(req)224 const c: Context = new Context(req)225226 it('Error on handler', async () => {227 const handler = () => {228 throw new Error()
40 unmodified lines
269 })270})271describe('compose with Context - not finalized', () => {272 const req = new Request('http://localhost/')274 const c: Context = new HonoContext(req)273 const c: Context = new Context(req)274 const onNotFound = (c: Context) => {275 return c.text('onNotFound', 404)276 }277
388 unmodified lines
modified:src/compose.ts+7 added-13 removed
1import { HonoContext } from './context'1import { Context } from './context'2import type { Environment, NotFoundHandler, ErrorHandler } from './types'3import type { Schema } from './validator/schema'34interface ComposeContext {5 finalized: boolean6 res: unknown7}89// Based on the code in the MIT licensed `koa-compose` package.11export const compose = <12 C extends ComposeContext,13 P extends string = string,14 E extends Partial<Environment> = Environment,15 D extends Partial<Schema> = Schema16>(10export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>(11 middleware: Function[],18 onNotFound?: NotFoundHandler<P, E, D>,19 onError?: ErrorHandler<P, E, D>12 onNotFound?: NotFoundHandler<E>,13 onError?: ErrorHandler<E>14) => {15 const middlewareLength = middleware.length16 return (context: C, next?: Function) => {17 let index = -1
10 unmodified lines
28 let res29 let isError = false3031 if (!handler) {38 if (context instanceof HonoContext && context.finalized === false && onNotFound) {32 if (context instanceof Context && context.finalized === false && onNotFound) {33 res = onNotFound(context)34 }35 } else {36 try {
1 unmodified line
38 const dispatchRes = dispatch(i + 1)39 return dispatchRes instanceof Promise ? dispatchRes : Promise.resolve(dispatchRes)40 })41 } catch (err) {48 if (err instanceof Error && context instanceof HonoContext && onError) {42 if (err instanceof Error && context instanceof Context && onError) {43 context.error = err44 res = onError(err, context)45 isError = true46 } else {
15 unmodified lines
62 }63 return context64 })65 .catch((err) => {72 if (err instanceof Error && context instanceof HonoContext && onError) {66 if (err instanceof Error && context instanceof Context && onError) {67 context.error = err68 context.res = onError(err, context)69 return context70 }
6 unmodified lines
modified:src/context.test.ts+8 added-8 removed
1import type { Context } from './context'2import { HonoContext } from './context'1//import type { Context } from './context'2import { Context } from './context'34describe('Context', () => {5 const req = new Request('http://localhost/')67 let c: Context8 beforeEach(() => {9 c = new HonoContext(req)9 c = new Context(req)10 })1112 it('c.text()', async () => {13 const res = c.text('text in c', 201, { 'X-Custom': 'Message' })
121 unmodified lines
135136 it('Should be able read env', async () => {137 const req = new Request('http://localhost/')138 const key = 'a-secret-key'139 const ctx = new HonoContext(req, {139 const ctx = new Context(req, {140 API_KEY: key,141 })142 expect(ctx.env.API_KEY).toBe(key)143 })144145 it('set and set', async () => {146 const ctx = new HonoContext(req)146 const ctx = new Context(req)147 expect(ctx.get('k-foo')).toEqual(undefined)148 ctx.set('k-foo', 'v-foo')149 expect(ctx.get('k-foo')).toEqual('v-foo')150 expect(ctx.get('k-bar')).toEqual(undefined)
1 unmodified line
152 expect(ctx.get('k-bar')).toEqual({ k: 'v' })153 })154155 it('has res object by default', async () => {156 c = new HonoContext(req)156 c = new Context(req)157 c.res.headers.append('foo', 'bar')158 const res = c.text('foo')159 expect(res.headers.get('foo')).not.toBeNull()160 expect(res.headers.get('foo')).toBe('bar')161 })162163 it('returns current runtime (node)', async () => {164 c = new HonoContext(req)164 c = new Context(req)165 expect(c.runtime).toBe('node')166 })167})168169describe('Context header', () => {170 const req = new Request('http://localhost/')171 let c: Context172 beforeEach(() => {173 c = new HonoContext(req)173 c = new Context(req)174 })175 it('Should return only one content-type value', async () => {176 c.header('Content-Type', 'foo')177 c.header('content-type', 'foo')
10 unmodified lines
modified:src/context.ts+4 added-43 removed
7 unmodified lines
8type Headers = Record<string, string | string[]>9type Runtime = 'node' | 'deno' | 'bun' | 'cloudflare' | 'fastly' | 'vercel' | 'other'10export type Data = string | ArrayBuffer | ReadableStream1112export interface Context<12export class Context<13 P extends string = string,14 E extends Partial<Environment> = Environment,15 S extends Partial<Schema> | unknown = Schema16> {17 req: Request<P, S extends Schema ? SchemaToProp<S> : any>18 env: E['Bindings']19 event: FetchEvent20 executionCtx: ExecutionContext19 finalized: boolean22 error: Error | undefined2324 get res(): Response25 set res(_res: Response)26 header: (name: string, value: string, options?: { append?: boolean }) => void27 status: (status: StatusCode) => void28 set: {29 <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void30 <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void31 (key: string, value: unknown): void32 }33 get: {34 <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]35 <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]36 <T = any>(key: string): T37 }38 pretty: (prettyJSON: boolean, space?: number) => void39 newResponse: (data: Data | null, status: StatusCode, headers: Headers) => Response40 body: (data: Data | null, status?: StatusCode, headers?: Headers) => Response41 text: (text: string, status?: StatusCode, headers?: Headers) => Response42 json: <T>(object: T, status?: StatusCode, headers?: Headers) => Response43 html: (html: string, status?: StatusCode, headers?: Headers) => Response44 redirect: (location: string, status?: StatusCode) => Response45 cookie: (name: string, value: string, options?: CookieOptions) => void46 notFound: () => Response | Promise<Response>47 get runtime(): Runtime48}4950export class HonoContext<51 P extends string = string,52 E extends Partial<Environment> = Environment,53 S extends Partial<Schema> = Schema54> implements Context<P, E, S>55{56 req: Request<P, S extends Schema ? SchemaToProp<S> : any>57 env: E['Bindings']58 finalized: boolean20 error: Error | undefined = undefined2122 _status: StatusCode = 20023 private _executionCtx: FetchEvent | ExecutionContext | undefined
1 unmodified line
25 private _prettySpace: number = 226 private _map: Record<string, unknown> | undefined27 private _headers: Record<string, string[]> | undefined28 private _res: Response | undefined68 private notFoundHandler: NotFoundHandler<P, E, S>29 private notFoundHandler: NotFoundHandler<E>3031 constructor(32 req: Request<P>,33 env: E['Bindings'] = {},34 executionCtx: FetchEvent | ExecutionContext | undefined = undefined,74 notFoundHandler: NotFoundHandler<P, E, S> = () => new Response()35 notFoundHandler: NotFoundHandler<E> = () => new Response()36 ) {37 this._executionCtx = executionCtx38 this.req = req as Request<P, S extends Schema ? SchemaToProp<S> : any>39 this.env = env || ({} as Bindings)
150 unmodified lines
190 this.header('set-cookie', cookie, { append: true })191 }192193 notFound(): Response | Promise<Response> {233 return this.notFoundHandler(this)194 return this.notFoundHandler(this as unknown as Context<string, E>)195 }196197 get runtime(): Runtime {198 // eslint-disable-next-line @typescript-eslint/no-explicit-any
29 unmodified lines
modified:src/hono.ts+11 added-15 removed
1import { compose } from './compose'2import type { Context } from './context'3import { HonoContext } from './context'2import { Context } from './context'3import { extendRequestPrototype } from './request'4import type { Router } from './router'5import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router'6import { RegExpRouter } from './router/reg-exp-router'
91 unmodified lines
9899 Object.assign(this, init)100 }101103 private notFoundHandler: NotFoundHandler<P, E, S> = (c: Context<P, E, S>) => {102 private notFoundHandler: NotFoundHandler<E> = (c: Context<string, E>) => {103 return c.text('404 Not Found', 404)104 }105107 private errorHandler: ErrorHandler<P, E, S> = (err: Error, c: Context<P, E, S>) => {106 private errorHandler: ErrorHandler<E> = (err: Error, c: Context<string, E>) => {107 console.trace(err.message)108 const message = 'Internal Server Error'109 return c.text(message, 500)110 }111112 // eslint-disable-next-line @typescript-eslint/no-explicit-any113 route(path: string, app?: Hono<E, P, S>) {113 route(path: string, app?: Hono<any>) {114 this._tempPath = path115 if (app) {116 app.routes.map((r) => {117 this.addRoute(r.method, r.path, r.handler)117 this.addRoute(r.method, r.path, r.handler as unknown as Handler<P, E>)118 })119 this._tempPath = ''120 }121 return this
17 unmodified lines
139 })140 return this141 }142143 onError(handler: ErrorHandler<P, E, S>) {143 onError(handler: ErrorHandler<E>) {144 this.errorHandler = handler145 return this146 }147148 notFound(handler: NotFoundHandler<P, E, S>) {148 notFound(handler: NotFoundHandler<E>) {149 this.notFoundHandler = handler150 return this151 }152
10 unmodified lines
163 private matchRoute(method: string, path: string) {164 return this.router.match(method, path)165 }166167 private handleError(err: unknown, c: Context<P, E, S>) {167 private handleError(err: unknown, c: Context<string, E, S>) {168 if (err instanceof Error) {169 return this.errorHandler(err, c)170 }171 throw err
9 unmodified lines
181182 const result = this.matchRoute(method, path)183 request.paramData = result?.params184185 const c = new HonoContext<P, E, S>(request, env, eventOrExecutionCtx, this.notFoundHandler)185 const c = new Context<string, E, S>(request, env, eventOrExecutionCtx, this.notFoundHandler)186187 // Do not `compose` if it has only one handler188 if (result && result.handlers.length === 1) {189 const handler = result.handlers[0]
22 unmodified lines
212 })()213 }214215 const handlers = result ? result.handlers : [this.notFoundHandler]216 const composed = compose<HonoContext<P, E, S>, P, E, S>(217 handlers,218 this.notFoundHandler,219 this.errorHandler220 )216 const composed = compose<Context<P, E, S>, E>(handlers, this.notFoundHandler, this.errorHandler)217218 return (async () => {219 try {220 const tmp = composed(c)
26 unmodified lines
modified:src/types.ts+7 added-10 removed
20 unmodified lines
21 E extends Partial<Environment> = Environment,22 S extends Partial<Schema> = Schema23> = (c: Context<P, E, S>, next: Next) => Promise<Response | undefined | void>2425export type NotFoundHandler<26 P extends string = string,27 E extends Partial<Environment> = Environment,28 S extends Partial<Schema> = Schema29> = (c: Context<P, E, S>) => Response | Promise<Response>25export type NotFoundHandler<E extends Partial<Environment> = Environment> = (26 c: Context<string, E>27) => Response | Promise<Response>2831export type ErrorHandler<32 P extends string = string,33 E extends Partial<Environment> = Environment,34 S extends Partial<Schema> = Schema35> = (err: Error, c: Context<P, E, S>) => Response29export type ErrorHandler<E extends Partial<Environment> = Environment> = (30 err: Error,31 c: Context<string, E>32) => Response3334export type Next = () => Promise<void>3536// eslint-disable-next-line @typescript-eslint/no-unused-vars
54 unmodified lines