Skip to content
Myr

refactor: refine code (#167)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parent a7b67e5 · Browse files · 9 files+62 added−47 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+62 added−47 removed

  • tests:+9 added−1 removed
  • other:+53 added−46 removed

9 files+62 added−47 removed

modified:src/middleware/body-parse/index.ts+6 added
modified:src/middleware/cookie/index.ts+1 added-1 removed
modified:src/middleware/graphql-server/parse-body.ts+1 added-1 removed
modified:src/middleware/mustache/index.ts+1 added-8 removed
1import type { Context } from '@/context'2import type { Next } from '@/hono'3import { bufferToString } from '@/utils/buffer'4import { getContentFromKVAsset, getKVFilePath } from '@/utils/cloudflare'56const EXTENSION = '.mustache'7const DEFAULT_DOCUMENT = 'index.mustache'
56 unmodified lines
6465 await next()66 }67}6768const bufferToString = (buffer: ArrayBuffer): string => {69 if (buffer instanceof ArrayBuffer) {70 const enc = new TextDecoder('utf-8')71 return enc.decode(buffer)72 }73 return buffer74}
modified:src/utils/buffer.test.ts+9 added-1 removed
modified:src/utils/buffer.ts+8 added
31 unmodified lines
32 const sa = await hashFunction(a)33 const sb = await hashFunction(b)34 return sa === sb && a === b35}3637export const bufferToString = (buffer: ArrayBuffer): string => {38 if (buffer instanceof ArrayBuffer) {39 const enc = new TextDecoder('utf-8')40 return enc.decode(buffer)41 }42 return buffer43}
modified:src/utils/cloudflare.ts+1 added-1 removed
1declare const __STATIC_CONTENT: KVNamespace, __STATIC_CONTENT_MANIFEST: string23export const getContentFromKVAsset = async (path: string): Promise<ArrayBuffer> => {4 let ASSET_MANIFEST: { [key: string]: string }4 let ASSET_MANIFEST: Record<string, string>5 if (typeof __STATIC_CONTENT_MANIFEST === 'string') {6 ASSET_MANIFEST = JSON.parse(__STATIC_CONTENT_MANIFEST)7 } else {8 ASSET_MANIFEST = __STATIC_CONTENT_MANIFEST
48 unmodified lines
modified:src/context.ts+21 added-20 removed
10 unmodified lines
11 req: Request<RequestParamKeyType>12 res: Response13 env: Env14 event: FetchEvent15 private _headers: Headers16 private _status: StatusCode17 private _statusText: string18 private _pretty: boolean19 private _prettySpace: number = 21516 #headers: Headers17 #status: StatusCode18 #statusText: string19 #pretty: boolean20 #prettySpace: number = 22122 render: (template: string, params?: object, options?: object) => Promise<Response>23 notFound: () => Response | Promise<Response>2425 constructor(
1 unmodified line
27 opts?: { res: Response; env: Env; event: FetchEvent }28 ) {29 this.req = this.initRequest(req)30 Object.assign(this, opts)30 this._headers = {}31 this.#headers = {}32 }3334 private initRequest<T>(req: Request<T>): Request<T> {35 req.header = (name: string): string => {
9 unmodified lines
45 header(name: string, value: string): void {46 if (this.res) {47 this.res.headers.set(name, value)48 }48 this._headers[name] = value49 this.#headers[name] = value50 }5152 status(status: StatusCode): void {53 if (this.res) {54 console.warn('c.res.status is already set.')55 return56 }56 this._status = status57 this._statusText = getStatusText(status)57 this.#status = status58 this.#statusText = getStatusText(status)59 }6061 pretty(prettyJSON: boolean, space: number = 2): void {61 this._pretty = prettyJSON62 this._prettySpace = space62 this.#pretty = prettyJSON63 this.#prettySpace = space64 }6566 newResponse(data: Data, init: ResponseInit = {}): Response {66 init.status = init.status || this._status || 20067 init.status = init.status || this.#status || 20068 init.statusText =68 init.statusText || this._statusText || getStatusText(init.status as StatusCode)69 init.statusText || this.#statusText || getStatusText(init.status as StatusCode)7070 init.headers = { ...this._headers, ...init.headers }71 init.headers = { ...this.#headers, ...init.headers }7273 // Content-Length74 let length = 075 if (data) {
8 unmodified lines
8485 return new Response(data, init)86 }8787 body(data: Data, status: StatusCode = this._status, headers: Headers = this._headers): Response {88 body(data: Data, status: StatusCode = this.#status, headers: Headers = this.#headers): Response {89 return this.newResponse(data, {90 status: status,91 headers: headers,92 })93 }9494 text(text: string, status: StatusCode = this._status, headers: Headers = {}): Response {95 text(text: string, status: StatusCode = this.#status, headers: Headers = {}): Response {96 if (typeof text !== 'string') {97 throw new TypeError('text method arg must be a string!')98 }99 headers['Content-Type'] ||= 'text/plain; charset=UTF-8'100 return this.body(text, status, headers)101 }102102 json(object: object, status: StatusCode = this._status, headers: Headers = {}): Response {103 json(object: object, status: StatusCode = this.#status, headers: Headers = {}): Response {104 if (typeof object !== 'object') {105 throw new TypeError('json method arg must be an object!')106 }106 const body = this._pretty107 ? JSON.stringify(object, null, this._prettySpace)107 const body = this.#pretty108 ? JSON.stringify(object, null, this.#prettySpace)109 : JSON.stringify(object)110 headers['Content-Type'] ||= 'application/json; charset=UTF-8'111 return this.body(body, status, headers)112 }113113 html(html: string, status: StatusCode = this._status, headers: Headers = {}): Response {114 html(html: string, status: StatusCode = this.#status, headers: Headers = {}): Response {115 if (typeof html !== 'string') {116 throw new TypeError('html method arg must be a string!')117 }118 headers['Content-Type'] ||= 'text/html; charset=UTF-8'
20 unmodified lines
modified:src/hono.ts+14 added-15 removed
9 unmodified lines
10 interface Request<ParamKeyType = string> {11 param: (key: ParamKeyType) => string12 query: (key: string) => string13 header: (name: string) => string14 parsedBody: any14 }15}1617export type Handler<RequestParamKeyType = string> = (
45 unmodified lines
63 'all'64) {65 readonly routerClass: { new (): Router<any> } = TrieRouter66 readonly strict: boolean = true // strict routing - default is true68 private router: Router<Handler>69 private middlewareRouters: Router<MiddlewareHandler>[]70 private tempPath: string67 #router: Router<Handler>68 #middlewareRouters: Router<MiddlewareHandler>[]69 #tempPath: string7071 constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {72 super()73
4 unmodified lines
78 })7980 Object.assign(this, init)8183 this.router = new this.routerClass()84 this.middlewareRouters = []85 this.tempPath = null82 this.#router = new this.routerClass()83 this.#middlewareRouters = []84 this.#tempPath = null85 }8687 private notFoundHandler: NotFoundHandler = (c: Context) => {88 const message = '404 Not Found'
7 unmodified lines
96 }9798 route(path: string): Hono {99 const newHono: Hono = new Hono()101 newHono.tempPath = path102 newHono.router = this.router100 newHono.#tempPath = path101 newHono.#router = this.#router102 return newHono103 }104105 use(path: string, middleware: MiddlewareHandler): void {
1 unmodified line
107 throw new TypeError('middleware must be a async function!')108 }109 const router = new this.routerClass()110 router.add(METHOD_NAME_OF_ALL, path, middleware)112 this.middlewareRouters.push(router)111 this.#middlewareRouters.push(router)112 }113114 onError(handler: ErrorHandler): Hono {115 this.errorHandler = handler
7 unmodified lines
123124 // addRoute('get', '/', handler)125 private addRoute(method: string, path: string, handler: Handler): Hono {126 method = method.toUpperCase()128 if (this.tempPath) {129 path = mergePath(this.tempPath, path)127 if (this.#tempPath) {128 path = mergePath(this.#tempPath, path)129 }131 this.router.add(method, path, handler)130 this.#router.add(method, path, handler)131 return this132 }133134 private async matchRoute(method: string, path: string): Promise<Result<Handler>> {136 return this.router.match(method, path)135 return this.#router.match(method, path)136 }137138 private async dispatch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {139 const path = getPathFromURL(request.url, { strict: this.strict })
9 unmodified lines
149 const handler = result ? result.handler : this.notFoundHandler150151 const middleware = []152154 for (const mr of this.middlewareRouters) {153 for (const mr of this.#middlewareRouters) {154 const mwResult = mr.match(METHOD_NAME_OF_ALL, path)155 if (mwResult) middleware.push(mwResult.handler)156 }157
39 unmodified lines