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
Provenance
- Commit
b41b1eb- Tree
bcba918- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
a7b67e5
9 files changed+62 added−47 removed
modified:src/middleware/body-parse/index.ts+6 added
12345678910111213142 unmodified linesimport type { Context } from '@/context'import type { Next } from '@/hono'import { parseBody } from '@/utils/body'
declare global { interface Request { parsedBody: any }}
export const bodyParse = () => { return async (ctx: Context, next: Next) => { ctx.req.parsedBody = await parseBody(ctx.req) await next()2 unmodified linesmodified:src/middleware/cookie/index.ts+1 added-1 removed
11 unmodified lines1213141516161718192067 unmodified lines11 unmodified lines cookie: (name: string, value: string, options?: CookieOptions) => void }}
export type Cookie = { [key: string]: string }export type Cookie = Record<string, string>export type CookieOptions = { domain?: string expires?: Date httpOnly?: boolean67 unmodified linesmodified:src/middleware/graphql-server/parse-body.ts+1 added-1 removed
11234524 unmodified linesexport async function parseBody(req: Request): Promise<{ [param: string]: unknown }> {export async function parseBody(req: Request): Promise<Record<string, unknown>> { const contentType = req.headers.get('content-type')
switch (contentType) { case 'application/graphql':24 unmodified linesmodified:src/middleware/mustache/index.ts+1 added-8 removed
1 import type { Context } from '@/context'2 import type { Next } from '@/hono'3+import { bufferToString } from '@/utils/buffer'4 import { getContentFromKVAsset, getKVFilePath } from '@/utils/cloudflare'5 6 const EXTENSION = '.mustache'7 const DEFAULT_DOCUMENT = 'index.mustache'56 unmodified lines64 65 await next()66 }67 }67-68-const 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
122345633 unmodified lines404142434445464748495051import { SHA256 as sha256CryptoJS } from 'crypto-js'import { timingSafeEqual } from '@/utils/buffer'import { timingSafeEqual, bufferToString } from '@/utils/buffer'
describe('buffer', () => { it('positive', async () => { expect(33 unmodified lines expect(await timingSafeEqual([1, 2], [1, 2])).toBe(false) expect(await timingSafeEqual([1, 2], [1, 2, 3])).toBe(false) })})
describe('bufferToString', () => { it('Should return あいうえお', () => { const bytes = [227, 129, 130, 227, 129, 132, 227, 129, 134, 227, 129, 136, 227, 129, 138] const buffer = Uint8Array.from(bytes).buffer expect(bufferToString(buffer)).toBe('あいうえお') })})modified:src/utils/buffer.ts+8 added
31 unmodified lines32 const sa = await hashFunction(a)33 const sb = await hashFunction(b)34 return sa === sb && a === b35 }36+37+export 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
1 declare const __STATIC_CONTENT: KVNamespace, __STATIC_CONTENT_MANIFEST: string2 3 export 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_MANIFEST48 unmodified linesmodified:src/context.ts+21 added-20 removed
10 unmodified lines11 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 = 215 16+ #headers: Headers17+ #status: StatusCode18+ #statusText: string19+ #pretty: boolean20+ #prettySpace: number = 221+22 render: (template: string, params?: object, options?: object) => Promise<Response>23 notFound: () => Response | Promise<Response>24 25 constructor(1 unmodified line27 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 }33 34 private initRequest<T>(req: Request<T>): Request<T> {35 req.header = (name: string): string => {9 unmodified lines45 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 }51 52 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 }60 61 pretty(prettyJSON: boolean, space: number = 2): void {61- this._pretty = prettyJSON62- this._prettySpace = space62+ this.#pretty = prettyJSON63+ this.#prettySpace = space64 }65 66 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)70 70- init.headers = { ...this._headers, ...init.headers }71+ init.headers = { ...this.#headers, ...init.headers }72 73 // Content-Length74 let length = 075 if (data) {8 unmodified lines84 85 return new Response(data, init)86 }87 87- 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 }94 94- 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 }102 102- 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 }113 113- 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 linesmodified:src/hono.ts+14 added-15 removed
9 unmodified lines10 interface Request<ParamKeyType = string> {11 param: (key: ParamKeyType) => string12 query: (key: string) => string13 header: (name: string) => string14- parsedBody: any14 }15 }16 17 export type Handler<RequestParamKeyType = string> = (45 unmodified lines63 '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: string70 71 constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {72 super()73 4 unmodified lines78 })79 80 Object.assign(this, init)81 83- this.router = new this.routerClass()84- this.middlewareRouters = []85- this.tempPath = null82+ this.#router = new this.routerClass()83+ this.#middlewareRouters = []84+ this.#tempPath = null85 }86 87 private notFoundHandler: NotFoundHandler = (c: Context) => {88 const message = '404 Not Found'7 unmodified lines96 }97 98 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 }104 105 use(path: string, middleware: MiddlewareHandler): void {1 unmodified line107 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 }113 114 onError(handler: ErrorHandler): Hono {115 this.errorHandler = handler7 unmodified lines123 124 // 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 }133 134 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 }137 138 private async dispatch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {139 const path = getPathFromURL(request.url, { strict: this.strict })9 unmodified lines149 const handler = result ? result.handler : this.notFoundHandler150 151 const middleware = []152 154- 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