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: pass context to onNotFound callback in serveStatic #1865

Merged
merged 5 commits into from
Jan 2, 2024
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
14 changes: 8 additions & 6 deletions deno_dist/adapter/deno/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import type { Context } from '../../context.ts'
import type { Next } from '../../types.ts'
import type { Env, MiddlewareHandler } from '../../types.ts'
import { getFilePath } from '../../utils/filepath.ts'
import { getMimeType } from '../../utils/mime.ts'

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { open } = Deno

export type ServeStaticOptions = {
export type ServeStaticOptions<E extends Env = Env> = {
root?: string
path?: string
rewriteRequestPath?: (path: string) => string
onNotFound?: (path: string) => void | Promise<void>
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>
}

const DEFAULT_DOCUMENT = 'index.html'

export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {
return async (c: Context, next: Next) => {
export const serveStatic = <E extends Env = Env>(
options: ServeStaticOptions<E> = { root: '' }
): MiddlewareHandler => {
return async (c, next) => {
// Do nothing if Response is already set
if (c.finalized) {
await next()
Expand Down Expand Up @@ -53,7 +55,7 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {
return c.body(file.readable)
}

await options.onNotFound?.(path)
await options.onNotFound?.(path, c)
await next()
return
}
Expand Down
5 changes: 4 additions & 1 deletion runtime_tests/bun/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ describe('Serve Static Middleware', () => {
const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))
expect(res.status).toBe(404)
expect(res.headers.get('X-Custom')).toBe('Bun')
expect(onNotFound).toHaveBeenCalledWith('./runtime_tests/bun/favicon-notfound.ico')
expect(onNotFound).toHaveBeenCalledWith(
'./runtime_tests/bun/favicon-notfound.ico',
expect.anything()
)
})

it('Should return 200 response - /static/plain.txt', async () => {
Expand Down
4 changes: 1 addition & 3 deletions runtime_tests/deno/middleware.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,7 @@ Deno.test('Serve Static middleware', async () => {
assertEquals(res.status, 404)
assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)
assertEquals(res.headers.get('X-Custom'), 'Deno')
assertSpyCall(onNotFound, 0, {
args: ['./runtime_tests/deno/favicon-notfound.ico'],
})
assertSpyCall(onNotFound, 0)

res = await app.request('http://localhost/static/plain.txt')
assertEquals(res.status, 200)
Expand Down
14 changes: 8 additions & 6 deletions src/adapter/bun/serve-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,26 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { existsSync } from 'fs'
import type { Context } from '../../context'
import type { Next } from '../../types'
import type { Env, MiddlewareHandler } from '../../types'
import { getFilePath } from '../../utils/filepath'
import { getMimeType } from '../../utils/mime'

// @ts-ignore
const { file } = Bun

export type ServeStaticOptions = {
export type ServeStaticOptions<E extends Env = Env> = {
root?: string
path?: string
rewriteRequestPath?: (path: string) => string
onNotFound?: (path: string) => void | Promise<void>
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>
}

const DEFAULT_DOCUMENT = 'index.html'

export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {
return async (c: Context, next: Next) => {
export const serveStatic = <E extends Env = Env>(
options: ServeStaticOptions<E> = { root: '' }
): MiddlewareHandler => {
return async (c, next) => {
// Do nothing if Response is already set
if (c.finalized) {
await next()
Expand Down Expand Up @@ -50,7 +52,7 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {
}
}

await options.onNotFound?.(path)
await options.onNotFound?.(path, c)
await next()
return
}
Expand Down
22 changes: 21 additions & 1 deletion src/adapter/cloudflare-workers/serve-static.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ describe('ServeStatic Middleware', () => {
it('Should return 404 response', async () => {
const res = await app.request('http://localhost/static/not-found.html')
expect(res.status).toBe(404)
expect(onNotFound).toHaveBeenCalledWith('assets/static/not-found.html')
expect(onNotFound).toHaveBeenCalledWith('assets/static/not-found.html', expect.anything())
})

it('Should return plan.txt', async () => {
Expand Down Expand Up @@ -155,3 +155,23 @@ describe('With middleware', () => {
expect(await res.text()).toBe('bar')
})
})

describe('Types of middleware', () => {
it('Should pass env type from generics of serveStatic', async () => {
type Env = {
Bindings: {
HOGE: string
}
}
const app = new Hono<Env>()
app.use(
'/static/*',
serveStatic<Env>({
root: './assets',
onNotFound: (_, c) => {
expectTypeOf(c.env).toEqualTypeOf<Env['Bindings']>()
},
})
)
})
})
13 changes: 8 additions & 5 deletions src/adapter/cloudflare-workers/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
// @denoify-ignore
import type { KVNamespace } from '@cloudflare/workers-types'
import type { MiddlewareHandler } from '../../types'
import type { Context } from '../../context'
import type { Env, MiddlewareHandler } from '../../types'
import { getFilePath } from '../../utils/filepath'
import { getMimeType } from '../../utils/mime'
import { getContentFromKVAsset } from './utils'

export type ServeStaticOptions = {
export type ServeStaticOptions<E extends Env = Env> = {
root?: string
path?: string
manifest?: object | string
namespace?: KVNamespace
rewriteRequestPath?: (path: string) => string
onNotFound?: (path: string) => void | Promise<void>
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>
}

const DEFAULT_DOCUMENT = 'index.html'

// This middleware is available only on Cloudflare Workers.
export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {
export const serveStatic = <E extends Env = Env>(
options: ServeStaticOptions<E> = { root: '' }
): MiddlewareHandler => {
return async (c, next) => {
// Do nothing if Response is already set
if (c.finalized) {
Expand Down Expand Up @@ -51,7 +54,7 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
return c.body(content)
}

await options.onNotFound?.(path)
await options.onNotFound?.(path, c)
await next()
return
}
Expand Down
5 changes: 3 additions & 2 deletions src/adapter/cloudflare-workers/server-static-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
// @ts-ignore
// For ES module mode
import manifest from '__STATIC_CONTENT_MANIFEST'
import type { Env } from '../../types'
import type { ServeStaticOptions } from './serve-static'
import { serveStatic } from './serve-static'

const module = (options: ServeStaticOptions = { root: '' }) => {
return serveStatic({
const module = <E extends Env = Env>(options: ServeStaticOptions<E> = { root: '' }) => {
return serveStatic<E>({
root: options.root,
path: options.path,
manifest: options.manifest ? options.manifest : manifest,
Expand Down
14 changes: 8 additions & 6 deletions src/adapter/deno/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import type { Context } from '../../context'
import type { Next } from '../../types'
import type { Env, MiddlewareHandler } from '../../types'
import { getFilePath } from '../../utils/filepath'
import { getMimeType } from '../../utils/mime'

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { open } = Deno

export type ServeStaticOptions = {
export type ServeStaticOptions<E extends Env = Env> = {
root?: string
path?: string
rewriteRequestPath?: (path: string) => string
onNotFound?: (path: string) => void | Promise<void>
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>
}

const DEFAULT_DOCUMENT = 'index.html'

export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {
return async (c: Context, next: Next) => {
export const serveStatic = <E extends Env = Env>(
options: ServeStaticOptions<E> = { root: '' }
): MiddlewareHandler => {
return async (c, next) => {
// Do nothing if Response is already set
if (c.finalized) {
await next()
Expand Down Expand Up @@ -53,7 +55,7 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {
return c.body(file.readable)
}

await options.onNotFound?.(path)
await options.onNotFound?.(path, c)
await next()
return
}
Expand Down
Loading