Skip to content
Myr

feat(types): keep schema info with `app.route()` (#909)

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

authored by Yusuke Wada · committed by GitHub · parent 7ffb5b5 · Browse files · 12 files+158 added−14 removed
This commit

State

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

Diff stats

12 files+158 added−14 removed

  • tests:+98 added−0 removed
  • other:+60 added−14 removed

12 files+158 added−14 removed

modified:deno_dist/client/client.ts+2 added-1 removed
modified:deno_dist/client/types.ts+3 added-2 removed
modified:deno_dist/hono.ts+8 added-3 removed
16 unmodified lines
17 Next,18 NotFoundHandler,19 OnHandlerInterface,20 TypedResponse,21 MergeSchemaPath,22 RemoveBlankRecord,23} from './types.ts'24import { getPathFromURL, mergePath } from './utils/url.ts'2526type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE
90 unmodified lines
117118 private notFoundHandler: NotFoundHandler = notFoundHandler119 private errorHandler: ErrorHandler = errorHandler120119 // eslint-disable-next-line @typescript-eslint/no-explicit-any120 route(path: string, app?: Hono<any, any>) {121 route<SubPath extends string, SubSchema>(122 path: SubPath,123 app?: Hono<E, SubSchema>124 ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>> {125 this._tempPath = path126 if (app) {127 app.routes.map((r) => {128 const handler =
4 unmodified lines
133 this.addRoute(r.method, r.path, handler)134 })135 this._tempPath = ''136 }137 // eslint-disable-next-line @typescript-eslint/no-explicit-any133 return this138 return this as any139 }140141 onError(handler: ErrorHandler<E>) {142 this.errorHandler = handler
127 unmodified lines
modified:deno_dist/types.ts+16 added
226 unmodified lines
227 ? { [MethodName in `$${Lowercase<K>}`]: R }228 : never229 : never230231export type MergeSchemaPath<S, P extends string> = S extends Record<infer Key, infer T>232 ? Key extends string233 ? Record<MergePath<P, Key>, T>234 : never235 : never236237export type MergePath<A extends string, B extends string> = A extends `${infer P}/`238 ? `${P}${B}`239 : `${A}${B}`240241////////////////////////////////////////242////// //////243////// TypedResponse //////244////// //////
66 unmodified lines
311////// //////312////////////////////////////////////////313314export type ExtractSchema<T> = T extends Hono<infer _, infer S> ? S : never315316export type RemoveBlankRecord<T> = T extends Record<infer K, unknown>317 ? K extends string318 ? T319 : never320 : never
modified:src/adapter/cloudflare-pages/handler.ts+1 added-1 removed
15 unmodified lines
1617export const handle: HandleInterface =18 <E extends Env>(subApp: Hono<E>, path: string = '/') =>19 ({ request, env, waitUntil }) =>20 new Hono()20 new Hono<E>()21 .route(path, subApp)22 .fetch(request, env, { waitUntil, passThroughOnException: () => {} })
modified:src/adapter/nextjs/handler.ts+1 added-1 removed
7 unmodified lines
89export const handle: HandleInterface =10 <E extends Env>(subApp: Hono<E>, path: string = '/') =>11 async (req) =>12 new Hono().route(path, subApp).fetch(req)12 new Hono<E>().route(path, subApp).fetch(req)
modified:src/client/client.test.ts+34 added
270 unmodified lines
271 }272 type verify = Expect<Equal<Expected, Actual['query']>>273 })274})275276describe('Merge path with `app.route()`', () => {277 const server = setupServer(278 rest.get('http://localhost/api/search', async (req, res, ctx) => {279 return res(280 ctx.status(200),281 ctx.json({282 ok: true,283 })284 )285 })286 )287288 beforeAll(() => server.listen())289 afterEach(() => server.resetHandlers())290 afterAll(() => server.close())291292 type Env = {293 Bindings: {294 TOKEN: string295 }296 }297298 it('Should have correct types', async () => {299 const api = new Hono<Env>().get('/search', (c) => c.jsonT({ ok: true }))300 const app = new Hono<Env>().route('/api', api)301 type AppType = typeof app302 const client = hc<AppType>('http://localhost')303 const res = await client.api.search.$get()304 const data = await res.json()305 type verify = Expect<Equal<boolean, typeof data.ok>>306 expect(data.ok).toBe(true)307 })308})
modified:src/client/client.ts+2 added-1 removed
98 unmodified lines
99 })100 }101}102103// eslint-disable-next-line @typescript-eslint/no-explicit-any103export const hc = <T extends Hono>(baseUrl: string, options?: RequestOptions) =>104export const hc = <T extends Hono<any>>(baseUrl: string, options?: RequestOptions) =>105 createProxy(async (opts) => {106 const parts = [...opts.path]107108 let method = ''
17 unmodified lines
modified:src/client/types.ts+3 added-2 removed
1import type { Hono } from '../hono'2import type { ValidationTargets, Env } from '../types'2import type { ValidationTargets } from '../types'34type MethodName = `$${string}`56type Endpoint = Record<MethodName, Data>
42 unmodified lines
49 E extends Record<string, unknown> ? E[Original] : never50 >51 }5253// eslint-disable-next-line @typescript-eslint/no-explicit-any53export type Client<T> = T extends Hono<Env, infer S>54export type Client<T> = T extends Hono<any, infer S>55 ? S extends Record<infer K, Endpoint>56 ? K extends string57 ? PathToChain<K, S>58 : never
14 unmodified lines
modified:src/hono.ts+8 added-3 removed
16 unmodified lines
17 Next,18 NotFoundHandler,19 OnHandlerInterface,20 TypedResponse,21 MergeSchemaPath,22 RemoveBlankRecord,23} from './types'24import { getPathFromURL, mergePath } from './utils/url'2526type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE
90 unmodified lines
117118 private notFoundHandler: NotFoundHandler = notFoundHandler119 private errorHandler: ErrorHandler = errorHandler120119 // eslint-disable-next-line @typescript-eslint/no-explicit-any120 route(path: string, app?: Hono<any, any>) {121 route<SubPath extends string, SubSchema>(122 path: SubPath,123 app?: Hono<E, SubSchema>124 ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>> {125 this._tempPath = path126 if (app) {127 app.routes.map((r) => {128 const handler =
4 unmodified lines
133 this.addRoute(r.method, r.path, handler)134 })135 this._tempPath = ''136 }137 // eslint-disable-next-line @typescript-eslint/no-explicit-any133 return this138 return this as any139 }140141 onError(handler: ErrorHandler<E>) {142 this.errorHandler = handler
127 unmodified lines
modified:src/types.test.ts+64 added
6 unmodified lines
7 Env,8 ExtractSchema,9 Handler,10 InputToDataByTarget,11 MergePath,12 MergeSchemaPath,13 MiddlewareHandler,14 ParamKeys,15 ParamKeyToRecord,16 RemoveQuestion,
319 unmodified lines
336 type verify = Expect<Equal<string, Actual>>337 })338 })339})340341describe('merge path', () => {342 test('MergePath', () => {343 type path1 = MergePath<'/api', '/book'>344 type verify1 = Expect<Equal<'/api/book', path1>>345 type path2 = MergePath<'/api/', '/book'>346 type verify2 = Expect<Equal<'/api/book', path2>>347 type path3 = MergePath<'/api/', '/'>348 type verify3 = Expect<Equal<'/api/', path3>>349 })350351 test('MergeSchemaPath', () => {352 type Sub = Schema<353 'post',354 '/posts',355 {356 json: {357 id: number358 title: string359 }360 },361 {362 message: string363 }364 > &365 Schema<366 'get',367 '/posts',368 {},369 {370 ok: boolean371 }372 >373374 type Actual = MergeSchemaPath<Sub, '/api'>375376 type Expected = {377 '/api/posts': {378 $post: {379 input: {380 json: {381 id: number382 title: string383 }384 }385 output: {386 message: string387 }388 }389 } & {390 $get: {391 input: {}392 output: {393 ok: boolean394 }395 }396 }397 }398399 type verify = Expect<Equal<Expected, Actual>>400 })401})
modified:src/types.ts+16 added
226 unmodified lines
227 ? { [MethodName in `$${Lowercase<K>}`]: R }228 : never229 : never230231export type MergeSchemaPath<S, P extends string> = S extends Record<infer Key, infer T>232 ? Key extends string233 ? Record<MergePath<P, Key>, T>234 : never235 : never236237export type MergePath<A extends string, B extends string> = A extends `${infer P}/`238 ? `${P}${B}`239 : `${A}${B}`240241////////////////////////////////////////242////// //////243////// TypedResponse //////244////// //////
66 unmodified lines
311////// //////312////////////////////////////////////////313314export type ExtractSchema<T> = T extends Hono<infer _, infer S> ? S : never315316export type RemoveBlankRecord<T> = T extends Record<infer K, unknown>317 ? K extends string318 ? T319 : never320 : never