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
Provenance
- Commit
2c5b989- Tree
043239b- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
7ffb5b5
12 files changed+158 added−14 removed
modified:deno_dist/client/client.ts+2 added-1 removed
98 unmodified lines9910010110210310310410510610710817 unmodified lines98 unmodified lines }) }}
// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const hc = <T extends Hono>(baseUrl: string, options?: RequestOptions) =>export const hc = <T extends Hono<any>>(baseUrl: string, options?: RequestOptions) => createProxy(async (opts) => { const parts = [...opts.path]
let method = ''17 unmodified linesmodified:deno_dist/client/types.ts+3 added-2 removed
122345642 unmodified lines495051525353545556575814 unmodified linesimport type { Hono } from '../hono.ts'import type { ValidationTargets, Env } from '../types.ts'import type { ValidationTargets } from '../types.ts'
type MethodName = `$${string}`
type Endpoint = Record<MethodName, Data>42 unmodified lines E extends Record<string, unknown> ? E[Original] : never > }
// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport type Client<T> = T extends Hono<Env, infer S>export type Client<T> = T extends Hono<any, infer S> ? S extends Record<infer K, Endpoint> ? K extends string ? PathToChain<K, S> : never14 unmodified linesmodified:deno_dist/hono.ts+8 added-3 removed
16 unmodified lines17 Next,18 NotFoundHandler,19 OnHandlerInterface,20 TypedResponse,21+ MergeSchemaPath,22+ RemoveBlankRecord,23 } from './types.ts'24 import { getPathFromURL, mergePath } from './utils/url.ts'25 26 type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE90 unmodified lines117 118 private notFoundHandler: NotFoundHandler = notFoundHandler119 private errorHandler: ErrorHandler = errorHandler120 119- // 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 lines133 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 }140 141 onError(handler: ErrorHandler<E>) {142 this.errorHandler = handler127 unmodified linesmodified:deno_dist/types.ts+16 added
226 unmodified lines227 ? { [MethodName in `$${Lowercase<K>}`]: R }228 : never229 : never230 231+export type MergeSchemaPath<S, P extends string> = S extends Record<infer Key, infer T>232+ ? Key extends string233+ ? Record<MergePath<P, Key>, T>234+ : never235+ : never236+237+export type MergePath<A extends string, B extends string> = A extends `${infer P}/`238+ ? `${P}${B}`239+ : `${A}${B}`240+241 ////////////////////////////////////////242 ////// //////243 ////// TypedResponse //////244 ////// //////66 unmodified lines311 ////// //////312 ////////////////////////////////////////313 314 export type ExtractSchema<T> = T extends Hono<infer _, infer S> ? S : never315+316+export type RemoveBlankRecord<T> = T extends Record<infer K, unknown>317+ ? K extends string318+ ? T319+ : never320+ : nevermodified:src/adapter/cloudflare-pages/handler.ts+1 added-1 removed
15 unmodified lines16 17 export 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 lines8 9 export 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 lines271 }272 type verify = Expect<Equal<Expected, Actual['query']>>273 })274 })275+276+describe('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+ )287+288+ beforeAll(() => server.listen())289+ afterEach(() => server.resetHandlers())290+ afterAll(() => server.close())291+292+ type Env = {293+ Bindings: {294+ TOKEN: string295+ }296+ }297+298+ 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 lines99 })100 }101 }102 103+// eslint-disable-next-line @typescript-eslint/no-explicit-any103-export const hc = <T extends Hono>(baseUrl: string, options?: RequestOptions) =>104+export const hc = <T extends Hono<any>>(baseUrl: string, options?: RequestOptions) =>105 createProxy(async (opts) => {106 const parts = [...opts.path]107 108 let method = ''17 unmodified linesmodified:src/client/types.ts+3 added-2 removed
1 import type { Hono } from '../hono'2-import type { ValidationTargets, Env } from '../types'2+import type { ValidationTargets } from '../types'3 4 type MethodName = `$${string}`5 6 type Endpoint = Record<MethodName, Data>42 unmodified lines49 E extends Record<string, unknown> ? E[Original] : never50 >51 }52 53+// eslint-disable-next-line @typescript-eslint/no-explicit-any53-export type Client<T> = T extends Hono<Env, infer S>54+export type Client<T> = T extends Hono<any, infer S>55 ? S extends Record<infer K, Endpoint>56 ? K extends string57 ? PathToChain<K, S>58 : never14 unmodified linesmodified:src/hono.ts+8 added-3 removed
16 unmodified lines17 Next,18 NotFoundHandler,19 OnHandlerInterface,20 TypedResponse,21+ MergeSchemaPath,22+ RemoveBlankRecord,23 } from './types'24 import { getPathFromURL, mergePath } from './utils/url'25 26 type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE90 unmodified lines117 118 private notFoundHandler: NotFoundHandler = notFoundHandler119 private errorHandler: ErrorHandler = errorHandler120 119- // 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 lines133 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 }140 141 onError(handler: ErrorHandler<E>) {142 this.errorHandler = handler127 unmodified linesmodified:src/types.test.ts+64 added
6 unmodified lines7 Env,8 ExtractSchema,9 Handler,10 InputToDataByTarget,11+ MergePath,12+ MergeSchemaPath,13 MiddlewareHandler,14 ParamKeys,15 ParamKeyToRecord,16 RemoveQuestion,319 unmodified lines336 type verify = Expect<Equal<string, Actual>>337 })338 })339 })340+341+describe('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+ })350+351+ 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+ >373+374+ type Actual = MergeSchemaPath<Sub, '/api'>375+376+ 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+ }398+399+ type verify = Expect<Equal<Expected, Actual>>400+ })401+})modified:src/types.ts+16 added
226 unmodified lines227 ? { [MethodName in `$${Lowercase<K>}`]: R }228 : never229 : never230 231+export type MergeSchemaPath<S, P extends string> = S extends Record<infer Key, infer T>232+ ? Key extends string233+ ? Record<MergePath<P, Key>, T>234+ : never235+ : never236+237+export type MergePath<A extends string, B extends string> = A extends `${infer P}/`238+ ? `${P}${B}`239+ : `${A}${B}`240+241 ////////////////////////////////////////242 ////// //////243 ////// TypedResponse //////244 ////// //////66 unmodified lines311 ////// //////312 ////////////////////////////////////////313 314 export type ExtractSchema<T> = T extends Hono<infer _, infer S> ? S : never315+316+export type RemoveBlankRecord<T> = T extends Record<infer K, unknown>317+ ? K extends string318+ ? T319+ : never320+ : never