chore(deno): denoify
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by Yusuke Wada · parent 2e3919a · Browse files · 4 files·+51 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+51 added−39 removed
- tests:+4 added−4 removed
- other:+47 added−35 removed
Provenance
- Commit
1ee08cc- Tree
8b38cf1- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
Yusuke Wada <yusuke@kamawada.com>- Parent
2e3919a
4 files changed+51 added−39 removed
modified:deno_dist/middleware/logger/index.ts+22 added-19 removed
123456789101156789101112131415161718192016212223192021222324252624252627282930313233353435363738394041424344454644474849505152535455565457585960619 unmodified linesimport type { Context } from '../../context.ts'import type { Next } from '../../hono.ts'import { getPathFromURL } from '../../utils/url.ts'
const humanize = (n: string[], opts?: { delimiter?: string; separator?: string }) => { const options = opts || {} const d = options.delimiter || ',' const s = options.separator || '.' n = n.toString().split('.') n[0] = n[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + d) return n.join(s)enum LogPrefix { Outgoing = '-->', Incoming = '<--', Error = 'xxx',}
const humanize = (times: string[]) => { const [delimiter, separator] = [',', '.']
const orderTimes = times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + delimiter))
return orderTimes.join(separator)}
const time = (start: number) => { const delta = Date.now() - start return humanize([delta < 10000 ? delta + 'ms' : Math.round(delta / 1000) + 's']) return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])}
const LogPrefix = { Outgoing: '-->', Incoming: '<--', Error: 'xxx',}
const colorStatus = (status: number = 0) => { const out: { [key: number]: string } = {const colorStatus = (status: number) => { const out: { [key: string]: string } = { 7: `\x1b[35m${status}\x1b[0m`, 5: `\x1b[31m${status}\x1b[0m`, 4: `\x1b[33m${status}\x1b[0m`, 3: `\x1b[36m${status}\x1b[0m`, 2: `\x1b[32m${status}\x1b[0m`, 1: `\x1b[32m${status}\x1b[0m`, 0: `\x1b[33m${status}\x1b[0m`, } return out[(status / 100) | 0]
const calculateStatus = (status / 100) | 0
return out[calculateStatus]}
type PrintFunc = (str: string, ...rest: string[]) => void
function log( fn: PrintFunc, prefix: string, method: string, path: string, status?: number, status: number = 0, elapsed?: string) { const out = prefix === LogPrefix.Incoming ? ` ${prefix} ${method} ${path}` : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}` fn(out)}
export const logger = (fn = console.log) => {export const logger = (fn: PrintFunc) => { return async (c: Context, next: Next) => { const { method } = c.req const path = getPathFromURL(c.req.url)
9 unmodified linesmodified:deno_dist/context.ts+20 added-10 removed
9 unmodified lines10 11 export interface Context<RequestParamKeyType extends string = string, E = Env> {12 req: Request<RequestParamKeyType>13 env: E14- event: FetchEvent | undefined15- executionCtx: ExecutionContext | undefined14+ event: FetchEvent15+ executionCtx: ExecutionContext16 finalized: boolean17 18 get res(): Response19 set res(_res: Response)16 unmodified lines36 implements Context<RequestParamKeyType, E>37 {38 req: Request<RequestParamKeyType>39 env: E40- event: FetchEvent | undefined41- executionCtx: ExecutionContext | undefined40 finalized: boolean41 42 _status: StatusCode = 20043+ private _executionCtx: FetchEvent | ExecutionContext | undefined44 private _pretty: boolean = false45 private _prettySpace: number = 246 private _map: Record<string, any> | undefined47 private _headers: Record<string, string> | undefined2 unmodified lines50 51 constructor(52 req: Request,53 env: E | undefined = undefined,55- eventOrExecutionCtx: FetchEvent | ExecutionContext | undefined = undefined,54+ executionCtx: FetchEvent | ExecutionContext | undefined = undefined,55 notFoundHandler: NotFoundHandler = () => new Response()56 ) {57+ this._executionCtx = executionCtx58 this.req = req59 this.env = env ? env : ({} as E)60 61- if (eventOrExecutionCtx && 'respondWith' in eventOrExecutionCtx) {62- this.event = eventOrExecutionCtx61+ this.notFoundHandler = notFoundHandler62+ this.finalized = false63+ }64+65+ get event(): FetchEvent {66+ if (this._executionCtx instanceof FetchEvent) {67+ return this._executionCtx68 } else {64- this.executionCtx = eventOrExecutionCtx69+ throw Error('This context has no FetchEvent')70 }71+ }72 67- this.notFoundHandler = notFoundHandler68- this.finalized = false73+ get executionCtx(): ExecutionContext {74+ if (this._executionCtx) {75+ return this._executionCtx76+ } else {77+ throw Error('This context has no ExecutionContext')78+ }79 }80 81 get res(): Response {82 return (this._res ||= new Response())91 unmodified linesmodified:src/middleware/logger/index.test.ts+4 added-4 removed
3 unmodified lines4567898910111213141516171818192021212223242551 unmodified lines3 unmodified linesdescribe('Logger by Middleware', () => { let app: Hono let log: string
beforeEach(() => { function sleep (time: number) { beforeEach(() => { function sleep(time: number) { return new Promise((resolve) => setTimeout(resolve, time)) }
app = new Hono()
const logFn = (str: string) => { log = str }
const shortRandomString = 'hono' const longRandomString = 'hono'.repeat(1000)
app.use('*', logger(logFn)) app.get('/short', (c) => c.text(shortRandomString)) app.get('/long', (c) => c.text(longRandomString)) app.get('/seconds', async (c) => {51 unmodified linesmodified:src/middleware/logger/index.ts+5 added-6 removed
2 unmodified lines3 import { getPathFromURL } from '../../utils/url'4 5 enum LogPrefix {6 Outgoing = '-->',7- Incoming ='<--',7+ Incoming = '<--',8 Error = 'xxx',9 }10 11 const humanize = (times: string[]) => {12 const [delimiter, separator] = [',', '.']13 14- const orderTimes = times.map(v => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + delimiter))15- 14+ const orderTimes = times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + delimiter))15+16 return orderTimes.join(separator)17 }18 19 const time = (start: number) => {20 const delta = Date.now() - start21 return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])22 }23 24-24 const colorStatus = (status: number) => {25 const out: { [key: string]: string } = {26 7: `\x1b[35m${status}\x1b[0m`,27 5: `\x1b[31m${status}\x1b[0m`,3 unmodified lines31 1: `\x1b[32m${status}\x1b[0m`,32 0: `\x1b[33m${status}\x1b[0m`,33 }34 36- const calculateStatus = (status / 100 | 0)35+ const calculateStatus = (status / 100) | 036 37 return out[calculateStatus]38 }39 26 unmodified lines66 await next()67 68 log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start))69 }71-}70+}