Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: route() with one argument is renamed basePath(). #964

Merged
merged 5 commits into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 33 additions & 20 deletions deno_dist/hono.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export class Hono<
routers: [new RegExpRouter(), new TrieRouter()],
})
readonly strict: boolean = true // strict routing - default is true
private basePath: string = ''
private _basePath: string = ''
private path: string = '*'

routes: RouterRoute[] = []
Expand Down Expand Up @@ -134,28 +134,41 @@ export class Hono<
private notFoundHandler: NotFoundHandler = notFoundHandler
private errorHandler: ErrorHandler = errorHandler

route<SubPath extends string, SubEnv extends Env, SubSchema>(
path: SubPath,
app: Hono<SubEnv, SubSchema>
): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath>
/** @deprecated
* Use `basePath` instead of `route` with one argument.
* The `route` with one argument has been removed in v4.
*/
route<SubPath extends string>(path: SubPath): Hono<E, RemoveBlankRecord<S>, BasePath>
route<SubPath extends string, SubEnv extends Env, SubSchema>(
path: SubPath,
app?: Hono<SubEnv, SubSchema>
): Hono<
E,
RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>,
MergePath<BasePath, SubPath>
> {
const subApp = this.clone()
subApp.basePath = mergePath(this.basePath, path)

if (app) {
app.routes.map((r) => {
const handler =
app.errorHandler === errorHandler
? r.handler
: async (c: Context, next: Next) =>
(await compose<Context>([r.handler], app.errorHandler)(c, next)).res
subApp.addRoute(r.method, r.path, handler)
})
): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath> {
const subApp = this.basePath(path)

if (!app) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return subApp as any
}

app.routes.map((r) => {
const handler =
app.errorHandler === errorHandler
? r.handler
: async (c: Context, next: Next) =>
(await compose<Context>([r.handler], app.errorHandler)(c, next)).res
subApp.addRoute(r.method, r.path, handler)
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return this as any
}

basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {
const subApp = this.clone()
subApp._basePath = mergePath(this._basePath, path)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return subApp as any
}
Expand All @@ -181,8 +194,8 @@ export class Hono<

private addRoute(method: string, path: string, handler: H) {
method = method.toUpperCase()
if (this.basePath) {
path = mergePath(this.basePath, path)
if (this._basePath) {
path = mergePath(this._basePath, path)
}
this.router.add(method, path, handler)
const r: RouterRoute = { path: path, method: method, handler: handler }
Expand Down
4 changes: 2 additions & 2 deletions src/adapter/cloudflare-pages/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ describe('Adapter for Cloudflare Pages', () => {
expect(await res.text()).toBe('/api/foo')
})

it('Should not use `route()` if path argument is not passed', async () => {
it('Should not use `basePath()` if path argument is not passed', async () => {
const request = new Request('http://localhost/api/error')
const app = new Hono().route('/api')
const app = new Hono().basePath('/api')

app.onError((e) => {
throw e
Expand Down
14 changes: 9 additions & 5 deletions src/adapter/cloudflare-pages/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,18 @@ type EventContext = {
}

interface HandleInterface {
<E extends Env>(app: Hono<E>, path?: string): (
eventContext: EventContext
) => Response | Promise<Response>
<E extends Env, S extends {}, BasePath extends string>(
app: Hono<E, S, BasePath>,
path?: string
): (eventContext: EventContext) => Response | Promise<Response>
}

export const handle: HandleInterface =
<E extends Env>(subApp: Hono<E>, path?: string) =>
<E extends Env, S extends {}, BasePath extends string>(
subApp: Hono<E, S, BasePath>,
path?: string
) =>
({ request, env, waitUntil }) => {
const app = path ? new Hono<E>().route(path, subApp) : subApp
const app = path ? new Hono<E, S, BasePath>().route(path, subApp as any) : subApp
return app.fetch(request, env, { waitUntil, passThroughOnException: () => {} })
}
2 changes: 1 addition & 1 deletion src/adapter/nextjs/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('Adapter for Next.js', () => {
})

it('Should not use `route()` if path argument is not passed', async () => {
const app = new Hono().route('/api')
const app = new Hono().basePath('/api')

app.onError((e) => {
throw e
Expand Down
11 changes: 8 additions & 3 deletions src/adapter/nextjs/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@ import { Hono } from '../../hono'
import type { Env } from '../../types'

interface HandleInterface {
<E extends Env>(subApp: Hono<E>, path?: string): (req: Request) => Response | Promise<Response>
<E extends Env, S extends {}, BasePath extends string>(subApp: Hono<E, S, BasePath>, path?: string): (
req: Request
) => Response | Promise<Response>
}

export const handle: HandleInterface =
<E extends Env>(subApp: Hono<E>, path?: string) =>
<E extends Env, S extends {}, BasePath extends string>(
subApp: Hono<E, S, BasePath>,
path?: string
) =>
(req) => {
const app = path ? new Hono<E>().route(path, subApp) : subApp
const app = path ? new Hono<E, S, BasePath>().route(path, subApp as any) : subApp
return app.fetch(req)
}
4 changes: 2 additions & 2 deletions src/client/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,8 @@ describe('Merge path with `app.route()`', () => {
expect(data.ok).toBe(true)
})

it('Should have correct types - route() then get()', async () => {
const base = new Hono<Env>().route('/api')
it('Should have correct types - basePath() then get()', async () => {
const base = new Hono<Env>().basePath('/api')
const app = base.get('/search', (c) => c.jsonT({ ok: true }))
type AppType = typeof app
const client = hc<AppType>('http://localhost')
Expand Down
26 changes: 23 additions & 3 deletions src/hono.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,18 +166,18 @@ describe('Routing', () => {
it('Nested route', async () => {
const app = new Hono()

const book = app.route('/book')
const book = app.basePath('/book')
book.get('/', (c) => c.text('get /book'))
book.get('/:id', (c) => {
return c.text('get /book/' + c.req.param('id'))
})
book.post('/', (c) => c.text('post /book'))

const user = app.route('/user')
const user = app.basePath('/user')
user.get('/login', (c) => c.text('get /user/login'))
user.post('/register', (c) => c.text('post /user/register'))

const appForEachUser = user.route(':id')
const appForEachUser = user.basePath(':id')
appForEachUser.get('/profile', (c) => c.text('get /user/' + c.req.param('id') + '/profile'))

app.get('/add-path-after-route-call', (c) => c.text('get /add-path-after-route-call'))
Expand Down Expand Up @@ -214,6 +214,26 @@ describe('Routing', () => {
expect(await res.text()).toBe('get /add-path-after-route-call')
})

it('Multiple route', async () => {
const app = new Hono()

const book = new Hono()
book.get('/hello', (c) => c.text('get /book/hello'))

const user = new Hono()
user.get('/hello', (c) => c.text('get /user/hello'))

app.route('/book', book).route('/user', user)

let res = await app.request('http://localhost/book/hello', { method: 'GET' })
expect(res.status).toBe(200)
expect(await res.text()).toBe('get /book/hello')

res = await app.request('http://localhost/user/hello', { method: 'GET' })
expect(res.status).toBe(200)
expect(await res.text()).toBe('get /user/hello')
})

describe('Nested route with middleware', () => {
const api = new Hono()
const api2 = api.use('*', async (_c, next) => await next())
Expand Down
53 changes: 33 additions & 20 deletions src/hono.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export class Hono<
routers: [new RegExpRouter(), new TrieRouter()],
})
readonly strict: boolean = true // strict routing - default is true
private basePath: string = ''
private _basePath: string = ''
private path: string = '*'

routes: RouterRoute[] = []
Expand Down Expand Up @@ -134,28 +134,41 @@ export class Hono<
private notFoundHandler: NotFoundHandler = notFoundHandler
private errorHandler: ErrorHandler = errorHandler

route<SubPath extends string, SubEnv extends Env, SubSchema>(
path: SubPath,
app: Hono<SubEnv, SubSchema>
): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath>
/** @deprecated
* Use `basePath` instead of `route` with one argument.
* The `route` with one argument has been removed in v4.
*/
route<SubPath extends string>(path: SubPath): Hono<E, RemoveBlankRecord<S>, BasePath>
route<SubPath extends string, SubEnv extends Env, SubSchema>(
path: SubPath,
app?: Hono<SubEnv, SubSchema>
): Hono<
E,
RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>,
MergePath<BasePath, SubPath>
> {
const subApp = this.clone()
subApp.basePath = mergePath(this.basePath, path)

if (app) {
app.routes.map((r) => {
const handler =
app.errorHandler === errorHandler
? r.handler
: async (c: Context, next: Next) =>
(await compose<Context>([r.handler], app.errorHandler)(c, next)).res
subApp.addRoute(r.method, r.path, handler)
})
): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath> {
const subApp = this.basePath(path)

if (!app) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return subApp as any
}

app.routes.map((r) => {
const handler =
app.errorHandler === errorHandler
? r.handler
: async (c: Context, next: Next) =>
(await compose<Context>([r.handler], app.errorHandler)(c, next)).res
subApp.addRoute(r.method, r.path, handler)
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return this as any
}

basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {
const subApp = this.clone()
subApp._basePath = mergePath(this._basePath, path)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return subApp as any
}
Expand All @@ -181,8 +194,8 @@ export class Hono<

private addRoute(method: string, path: string, handler: H) {
method = method.toUpperCase()
if (this.basePath) {
path = mergePath(this.basePath, path)
if (this._basePath) {
path = mergePath(this._basePath, path)
}
this.router.add(method, path, handler)
const r: RouterRoute = { path: path, method: method, handler: handler }
Expand Down