fix: fixed the issue logger called twice (#494)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix: fixed the issue logger called twice * add handling the error and shorten code
authored by Yusuke Wada · committed by GitHub · parent 9793e6b · Browse files · 9 files·+74 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
9 files+74 added−30 removed
- tests:+36 added−0 removed
- other:+38 added−30 removed
Provenance
- Commit
24a2894- Tree
60d7613- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
9793e6b
9 files changed+74 added−30 removed
modified:deno_dist/deno/serve-static.ts+1 added-1 removed
11 unmodified lines1213141516161718192023 unmodified lines11 unmodified lines
export const serveStatic = (options: ServeStaticOptions = { root: '' }) => { return async (c: Context, next: Next): Promise<Response | undefined> => { // Do nothing if Response is already set if (c.res && c.finalized) { if (c.finalized) { await next() }
const url = new URL(c.req.url)23 unmodified linesmodified:deno_dist/middleware/serve-static/serve-static.ts+1 added-1 removed
15 unmodified lines1617181920202122232425 unmodified lines15 unmodified lines// This middleware is available only on Cloudflare Workers.export const serveStatic = (options: ServeStaticOptions = { root: '' }) => { return async (c: Context, next: Next): Promise<Response | undefined> => { // Do nothing if Response is already set if (c.res && c.finalized) { if (c.finalized) { await next() }
const url = new URL(c.req.url)25 unmodified linesmodified:deno_dist/context.ts+2 added-1 removed
1 import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono.ts'2+import { defaultNotFoundMessage } from './hono.ts'3 import type { CookieOptions } from './utils/cookie.ts'4 import { serialize } from './utils/cookie.ts'5 import type { StatusCode } from './utils/http-status.ts'6 import { isAbsoluteURL } from './utils/url.ts'84 unmodified lines91 }92 }93 94 get res(): Response {94- return (this._res ||= new Response())95+ return (this._res ||= new Response(defaultNotFoundMessage, { status: 404 }))96 }97 98 set res(_res: Response) {99 this._res = _res93 unmodified linesmodified:deno_dist/hono.ts+15 added-12 removed
33 unmodified lines34 ) => Response35 36 export type Next = () => Promise<void>37 38+export const defaultNotFoundMessage = '404 Not Found'39+40 // eslint-disable-next-line @typescript-eslint/no-unused-vars41 type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`42 ? Name43 : NameWithPattern80 unmodified lines124 Object.assign(this, init)125 }126 127 private notFoundHandler: NotFoundHandler = (c: Context) => {126- const message = '404 Not Found'128+ const message = defaultNotFoundMessage129 return c.text(message, 404)130 }131 132 private errorHandler: ErrorHandler = (err: Error, c: Context) => {73 unmodified lines206 // Do not `compose` if it has only one handler207 if (result && result.handlers.length === 1) {208 const handler = result.handlers[0]209 try {208- const response = handler(c, async () => {})209- if (response) {210- if (response instanceof Promise) {211- const awaited = await response212- if (awaited) return awaited213- } else {214- return response215- }210+ const res = handler(c, async () => {})211+ if (res) {212+ const awaited = res instanceof Promise ? await res : res213+ if (awaited) return awaited214 }217- // Do nothing218- } catch {}215+ return this.notFoundHandler(c as Context)216+ } catch (err) {217+ if (err instanceof Error) {218+ return this.errorHandler(err, c as Context)219+ }220+ throw err221+ }222 }223 224 const handlers = result ? result.handlers : [this.notFoundHandler]225 7 unmodified lines233 )234 }235 } catch (err) {236 if (err instanceof Error) {234- return this.errorHandler(err, c as Context<string, Environment>)237+ return this.errorHandler(err, c as Context)238 }239 throw err240 }241 16 unmodified linesmodified:src/deno/serve-static.ts+1 added-1 removed
11 unmodified lines1213141516161718192023 unmodified lines11 unmodified lines
export const serveStatic = (options: ServeStaticOptions = { root: '' }) => { return async (c: Context, next: Next): Promise<Response | undefined> => { // Do nothing if Response is already set if (c.res && c.finalized) { if (c.finalized) { await next() }
const url = new URL(c.req.url)23 unmodified linesmodified:src/middleware/serve-static/serve-static.ts+1 added-1 removed
15 unmodified lines1617181920202122232425 unmodified lines15 unmodified lines// This middleware is available only on Cloudflare Workers.export const serveStatic = (options: ServeStaticOptions = { root: '' }) => { return async (c: Context, next: Next): Promise<Response | undefined> => { // Do nothing if Response is already set if (c.res && c.finalized) { if (c.finalized) { await next() }
const url = new URL(c.req.url)25 unmodified linesmodified:src/context.ts+2 added-1 removed
1 import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono'2+import { defaultNotFoundMessage } from './hono'3 import type { CookieOptions } from './utils/cookie'4 import { serialize } from './utils/cookie'5 import type { StatusCode } from './utils/http-status'6 import { isAbsoluteURL } from './utils/url'84 unmodified lines91 }92 }93 94 get res(): Response {94- return (this._res ||= new Response())95+ return (this._res ||= new Response(defaultNotFoundMessage, { status: 404 }))96 }97 98 set res(_res: Response) {99 this._res = _res93 unmodified linesmodified:src/hono.test.ts+36 added
1 import type { Context } from './context'2 import type { Next } from './hono'3 import { Hono } from './hono'4+import { logger } from './middleware/logger'5 import { poweredBy } from './middleware/powered-by'6 7 describe('GET Request', () => {8 const app = new Hono()1048 unmodified lines1057 expect(await res.text()).toBe('Bar')1058 expect(res.headers.get('content-type')).toBe('text/plain; charset=UTF-8')1059 })1060 })1061+1062+describe('Count of logger called', () => {1063+ // It will be added `2` each time the logger is called once.1064+ let count = 01065+ let log = ''1066+1067+ const app = new Hono()1068+1069+ const logFn = (str: string) => {1070+ count++1071+ log = str1072+ }1073+1074+ app.use('*', logger(logFn))1075+ app.get('/', (c) => c.text('foo'))1076+1077+ it('Should be called two times', async () => {1078+ const res = await app.request('http://localhost/not-found')1079+ expect(res).not.toBeNull()1080+ expect(res.status).toBe(404)1081+ expect(await res.text()).toBe('404 Not Found')1082+ expect(count).toBe(2)1083+ expect(log).toMatch(/404/)1084+ })1085+1086+ it('Should be called two times / Custom Not Found', async () => {1087+ app.notFound((c) => c.text('Custom Not Found', 404))1088+ const res = await app.request('http://localhost/custom-not-found')1089+ expect(res).not.toBeNull()1090+ expect(res.status).toBe(404)1091+ expect(await res.text()).toBe('Custom Not Found')1092+ expect(count).toBe(4)1093+ expect(log).toMatch(/404/)1094+ })1095+})modified:src/hono.ts+15 added-12 removed
33 unmodified lines34 ) => Response35 36 export type Next = () => Promise<void>37 38+export const defaultNotFoundMessage = '404 Not Found'39+40 // eslint-disable-next-line @typescript-eslint/no-unused-vars41 type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`42 ? Name43 : NameWithPattern80 unmodified lines124 Object.assign(this, init)125 }126 127 private notFoundHandler: NotFoundHandler = (c: Context) => {126- const message = '404 Not Found'128+ const message = defaultNotFoundMessage129 return c.text(message, 404)130 }131 132 private errorHandler: ErrorHandler = (err: Error, c: Context) => {73 unmodified lines206 // Do not `compose` if it has only one handler207 if (result && result.handlers.length === 1) {208 const handler = result.handlers[0]209 try {208- const response = handler(c, async () => {})209- if (response) {210- if (response instanceof Promise) {211- const awaited = await response212- if (awaited) return awaited213- } else {214- return response215- }210+ const res = handler(c, async () => {})211+ if (res) {212+ const awaited = res instanceof Promise ? await res : res213+ if (awaited) return awaited214 }217- // Do nothing218- } catch {}215+ return this.notFoundHandler(c as Context)216+ } catch (err) {217+ if (err instanceof Error) {218+ return this.errorHandler(err, c as Context)219+ }220+ throw err221+ }222 }223 224 const handlers = result ? result.handlers : [this.notFoundHandler]225 7 unmodified lines233 )234 }235 } catch (err) {236 if (err instanceof Error) {234- return this.errorHandler(err, c as Context<string, Environment>)237+ return this.errorHandler(err, c as Context)238 }239 throw err240 }241 16 unmodified lines