feat: pass context to onNotFound callback in serveStatic (#1865)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: pass context to onNotFound callback in serveStatic * chore: denoify * test: update notFoundHandler's callback expect * feat: add Env generics for serveStatic to support `c.env` type in callback handler * feat: add Env generics for serveStatic to support c.env type in cloudflare workers module's callback handler
authored by Sor4chi · committed by GitHub · parent 0e7f519 · Browse files · 8 files·+61 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+61 added−30 removed
- tests:+26 added−5 removed
- other:+35 added−25 removed
Provenance
- Commit
b8b0b38- Tree
c4effc5- Author
Sor4chi <80559385+sor4chi@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
0e7f519
8 files changed+61 added−30 removed
modified:deno_dist/adapter/deno/serve-static.ts+8 added-6 removed
122345678910101112131414151617181920192021222324252627 unmodified lines54555657565859606162import 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-ignoreconst { 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() return27 unmodified lines // Return Response object with stream return c.body(file.readable) }
await options.onNotFound?.(path) await options.onNotFound?.(path, c) await next() return }}modified:runtime_tests/bun/index.test.tsx+4 added-1 removed
112 unmodified lines113 it('Should return 404 response', async () => {114 const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))115 expect(res.status).toBe(404)116 expect(res.headers.get('X-Custom')).toBe('Bun')117- expect(onNotFound).toHaveBeenCalledWith('./runtime_tests/bun/favicon-notfound.ico')117+ expect(onNotFound).toHaveBeenCalledWith(118+ './runtime_tests/bun/favicon-notfound.ico',119+ expect.anything()120+ )121 })122 123 it('Should return 200 response - /static/plain.txt', async () => {124 const res = await app.request(new Request('http://localhost/static/plain.txt'))85 unmodified linesmodified:runtime_tests/deno/middleware.test.tsx+1 added-3 removed
100 unmodified lines101 res = await app.request('http://localhost/favicon-notfound.ico')102 assertEquals(res.status, 404)103 assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)104 assertEquals(res.headers.get('X-Custom'), 'Deno')105- assertSpyCall(onNotFound, 0, {106- args: ['./runtime_tests/deno/favicon-notfound.ico'],107- })105+ assertSpyCall(onNotFound, 0)106 107 res = await app.request('http://localhost/static/plain.txt')108 assertEquals(res.status, 200)109 assertEquals(await res.text(), 'Deno!')34 unmodified linesmodified:src/adapter/bun/serve-static.ts+8 added-6 removed
1234556789101112121314151616171819202122212223242526272822 unmodified lines51525354535556575859// @denoify-ignore/* 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-ignoreconst { 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() return22 unmodified lines return c.body(content) } }
await options.onNotFound?.(path) await options.onNotFound?.(path, c) await next() return }}modified:src/adapter/cloudflare-workers/serve-static.test.ts+21 added-1 removed
61 unmodified lines62 63 it('Should return 404 response', async () => {64 const res = await app.request('http://localhost/static/not-found.html')65 expect(res.status).toBe(404)66- expect(onNotFound).toHaveBeenCalledWith('assets/static/not-found.html')66+ expect(onNotFound).toHaveBeenCalledWith('assets/static/not-found.html', expect.anything())67 })68 69 it('Should return plan.txt', async () => {70 const res = await app.request('http://localhost/static-no-root/plain.txt')83 unmodified lines154 expect(res.status).toBe(200)155 expect(await res.text()).toBe('bar')156 })157 })158+159+describe('Types of middleware', () => {160+ it('Should pass env type from generics of serveStatic', async () => {161+ type Env = {162+ Bindings: {163+ HOGE: string164+ }165+ }166+ const app = new Hono<Env>()167+ app.use(168+ '/static/*',169+ serveStatic<Env>({170+ root: './assets',171+ onNotFound: (_, c) => {172+ expectTypeOf(c.env).toEqualTypeOf<Env['Bindings']>()173+ },174+ })175+ )176+ })177+})modified:src/adapter/cloudflare-workers/serve-static.ts+8 added-5 removed
12334567889101112131414151617181920202122232425262725 unmodified lines53545556545758596061// @denoify-ignoreimport type { KVNamespace } from '@cloudflare/workers-types'import type { Context } from '../../context'import type { MiddlewareHandler } from '../../types'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) { await next()25 unmodified lines // Return Response object return c.body(content) }
await options.onNotFound?.(path) await options.onNotFound?.(path, c) await next() return }}modified:src/adapter/cloudflare-workers/server-static-module.ts+3 added-2 removed
1 unmodified line2 // eslint-disable-next-line @typescript-eslint/ban-ts-comment3 // @ts-ignore4 // For ES module mode5 import manifest from '__STATIC_CONTENT_MANIFEST'6+import type { Env } from '../../types'7 import type { ServeStaticOptions } from './serve-static'8 import { serveStatic } from './serve-static'9 9-const module = (options: ServeStaticOptions = { root: '' }) => {10- return serveStatic({10+const module = <E extends Env = Env>(options: ServeStaticOptions<E> = { root: '' }) => {11+ return serveStatic<E>({12 root: options.root,13 path: options.path,14 manifest: options.manifest ? options.manifest : manifest,15 rewriteRequestPath: options.rewriteRequestPath,4 unmodified linesmodified:src/adapter/deno/serve-static.ts+8 added-6 removed
1 import type { Context } from '../../context'2-import type { Next } from '../../types'2+import type { Env, MiddlewareHandler } from '../../types'3 import { getFilePath } from '../../utils/filepath'4 import { getMimeType } from '../../utils/mime'5 6 // eslint-disable-next-line @typescript-eslint/ban-ts-comment7 // @ts-ignore8 const { open } = Deno9 10-export type ServeStaticOptions = {10+export type ServeStaticOptions<E extends Env = Env> = {11 root?: string12 path?: string13 rewriteRequestPath?: (path: string) => string14- onNotFound?: (path: string) => void | Promise<void>14+ onNotFound?: (path: string, c: Context<E>) => void | Promise<void>15 }16 17 const DEFAULT_DOCUMENT = 'index.html'18 19-export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {20- return async (c: Context, next: Next) => {19+export const serveStatic = <E extends Env = Env>(20+ options: ServeStaticOptions<E> = { root: '' }21+): MiddlewareHandler => {22+ return async (c, next) => {23 // Do nothing if Response is already set24 if (c.finalized) {25 await next()26 return27 unmodified lines54 // Return Response object with stream55 return c.body(file.readable)56 }57 56- await options.onNotFound?.(path)58+ await options.onNotFound?.(path, c)59 await next()60 return61 }62 }