refactor: enable `strictPropertyInitialization` (#333)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* refactor: enable `strictPropertyInitialization` * checkout `0de127fd74879445b0910fd6505ca22a22a5d791`
authored by Yusuke Wada · committed by GitHub · parent 11d3d4e · Browse files · 11 files·+78 added−68 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+78 added−68 removed
- tests:+6 added−5 removed
- other:+72 added−63 removed
Provenance
- Commit
1282473- Tree
843555d- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
11d3d4e
11 files changed+78 added−68 removed
modified:src/middleware/body-parse/index.test.ts+3 added-5 removed
123234518 unmodified lines242526273028293031325 unmodified lines383940414442434445468 unmodified lines555657586159606162import { Hono } from '../../hono'import type { HonoRequest } from '../../request'import { extendHonoRequest } from '../../request'import { bodyParse } from '.'
describe('Parse Body Middleware', () => { const app = new Hono()18 unmodified lines }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(extendHonoRequest(req as HonoRequest).parsedBody).toEqual(payload) expect(req.parsedBody).toEqual(payload) expect(await res.json()).toEqual(payload) })
it('POST with text', async () => {5 unmodified lines }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(extendHonoRequest(req as HonoRequest).parsedBody).toEqual(payload) expect(req.parsedBody).toEqual(payload) expect(await res.text()).toEqual(payload) })
it('POST with form', async () => {8 unmodified lines }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(extendHonoRequest(req as HonoRequest).parsedBody).toEqual({ message: 'hello' }) expect(req.parsedBody).toEqual({ message: 'hello' }) expect(await res.json()).toEqual({ message: 'hello' }) })})modified:src/middleware/body-parse/index.ts+2 added-2 removed
12345656789106 unmodified linesimport type { Context } from '../../context'import type { Next } from '../../hono'import { parseBody } from '../../utils/body'
declare module '../../request' { interface HonoRequest {declare global { interface Request { parsedBody: any }}
6 unmodified linesmodified:src/middleware/cookie/index.ts+2 added-2 removed
1234545678985 unmodified linesimport type { Context } from '../../context'import type { Next } from '../../hono'
declare module '../../request' { interface HonoRequest {declare global { interface Request { cookie: { (name: string): string (): Record<string, string> }85 unmodified linesmodified:src/middleware/mustache/mustache.ts+6 added
12 unmodified lines13 interface Mustache {14 render: (content: string, params: object, partials: Partials) => string15 }16 17+declare module '../../context' {18+ interface Context {19+ render: (content: string, params?: object, options?: object) => Response | Promise<Response>20+ }21+}22+23 export type MustacheOptions = {24 root: string25 manifest?: object | string26 namespace?: KVNamespace49 unmodified linesmodified:src/router/trie-router/node.ts+1 added
35 unmodified lines36 37 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {38 this.children = children || {}39 this.methods = []40+ this.name = ''41 if (method && handler) {42 const m: Record<string, HandlerSet<T>> = {}43 m[method] = { handler: handler, score: 0, name: this.name }44 this.methods = [m]159 unmodified linesmodified:src/compose.test.ts+3 added
1 import { compose } from './compose'2 import { Context } from './context'3+import { extendRequestPrototype } from './request'4 5+extendRequestPrototype()6+7 type C = {8 req: Record<string, string>9 res: Record<string, string>10 }666 unmodified linesmodified:src/context.ts+6 added-17 removed
1 import type { NotFoundHandler } from './hono'2-import { extendHonoRequest } from './request'3-import type { HonoRequest } from './request'2 import type { StatusCode } from './utils/http-status'3 import { isAbsoluteURL } from './utils/url'4 5 type Headers = Record<string, string>1 unmodified line7 8 export type Env = Record<string, any>9 10 export class Context<RequestParamKeyType extends string = string, E = Env> {13- req: HonoRequest<RequestParamKeyType>11+ req: Request<RequestParamKeyType>12 env: E13 event: FetchEvent | undefined14 executionCtx: ExecutionContext | undefined15 finalized: boolean5 unmodified lines21 private _headers: Record<string, string> | undefined22 private _res: Response | undefined23 private notFoundHandler: NotFoundHandler24 27- render: (content: string, params?: object, options?: object) => Response | Promise<Response>28-25 constructor(30- req: HonoRequest | Request,26+ req: Request,27 env: E | undefined = undefined,28 eventOrExecutionCtx: FetchEvent | ExecutionContext | undefined = undefined,29 notFoundHandler: NotFoundHandler = () => new Response()30 ) {35- if (req instanceof Request) {36- this.req = extendHonoRequest(req as HonoRequest)37- } else {38- this.req = req39- }31+ this.req = req32+ this.env = env ? env : ({} as E)33 41- if (env) {42- this.env = env43- }44-45- this.executionCtx = eventOrExecutionCtx46-34 if (eventOrExecutionCtx && 'respondWith' in eventOrExecutionCtx) {35 this.event = eventOrExecutionCtx36+ } else {37+ this.executionCtx = eventOrExecutionCtx38 }39 40 this.notFoundHandler = notFoundHandler41 this.finalized = false90 unmodified linesmodified:src/hono.ts+6 added-12 removed
1 import { compose } from './compose'2 import { Context } from './context'3 import type { Env } from './context'4-import type { HonoRequest } from './request'5-import { extendHonoRequest } from './request'4+import { extendRequestPrototype } from './request'5 import type { Router } from './router'6 import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'7 import { TrieRouter } from './router/trie-router' // Default Router8 import { getPathFromURL, mergePath } from './utils/url'64 unmodified lines73 74 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {75 super()76 77+ extendRequestPrototype()78+79 const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]80 allMethods.map((method) => {81 this[method] = <Path extends string = ''>(82 args1: Path | Handler<ParamKeys<Path>, E>,78 unmodified lines161 }162 163 private async dispatch(164 request: Request,164- executionCtx?: ExecutionContext,165+ eventOrExecutionCtx?: ExecutionContext | FetchEvent,166 env?: E167 ): Promise<Response> {167- request = extendHonoRequest(request as HonoRequest)168 const path = getPathFromURL(request.url, this.strict)169 const method = request.method170 171 const result = this.matchRoute(method, path)172- ;(request as HonoRequest).paramData = result?.params172+ request.paramData = result?.params173 174 const handlers = result ? result.handlers : [this.notFoundHandler]175 176- const c = new Context<string, E>(request, env, executionCtx, this.notFoundHandler)176+ const c = new Context<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)177 178 const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)179 let context: Context180 try {24 unmodified lines205 request(input: RequestInfo, requestInit?: RequestInit): Promise<Response> {206 const req = input instanceof Request ? input : new Request(input, requestInit)207 return this.dispatch(req)208 }209-210- fire(): void {211- addEventListener('fetch', (event: FetchEvent): void => {212- event.respondWith(this.handleEvent(event))213- })214- }209 }modified:src/index.ts+15 added-1 removed
1 // eslint-disable-next-line @typescript-eslint/triple-slash-reference2 /// <reference path="./request.ts" /> Import "declare global" for the Request interface.3 4-export { Hono } from './hono'4+import { Hono } from './hono'5 export type { Handler, Next } from './hono'6 export { Context } from './context'7 export type { Env } from './context'8+9+declare module './hono' {10+ interface Hono {11+ fire(): void12+ }13+}14+15+Hono.prototype.fire = function () {16+ addEventListener('fetch', (event: FetchEvent): void => {17+ void event.respondWith(this.handleEvent(event))18+ })19+}20+21+export { Hono }modified:src/request.ts+33 added-28 removed
1+declare global {1-export class HonoRequest<ParamKeyType extends string = string> extends Request {2- param: {3- (key: ParamKeyType): string4- (): Record<ParamKeyType, string>2+ interface Request<ParamKeyType extends string = string> {3+ param: {4+ (key: ParamKeyType): string5+ (): Record<ParamKeyType, string>6+ }7+ paramData?: Record<ParamKeyType, string>8+ query: {9+ (key: string): string10+ (): Record<string, string>11+ }12+ queries: {13+ (key: string): string[]14+ (): Record<string, string[]>15+ }16+ header: {17+ (name: string): string18+ (): Record<string, string>19+ }20 }6- paramData?: Record<ParamKeyType, string>7- query: {8- (key: string): string9- (): Record<string, string>10- }11- queries: {12- (key: string): string[]13- (): Record<string, string[]>14- }15- header: {16- (name: string): string17- (): Record<string, string>18- }21 }22 21-export function extendHonoRequest(request: HonoRequest): HonoRequest {22- request.param = function (this: HonoRequest, key?: string) {23+export function extendRequestPrototype() {24+ if (!!Request.prototype.param as boolean) {25+ // already extended26+ return27+ }28+29+ Request.prototype.param = function (this: Request, key?: string) {30 if (this.paramData) {31 if (key) {32 return this.paramData[key]33 } else {34 return this.paramData35 }36 }37 return null31- } as InstanceType<typeof HonoRequest>['param']38+ } as InstanceType<typeof Request>['param']39 33- request.header = function (this: HonoRequest, name?: string) {40+ Request.prototype.header = function (this: Request, name?: string) {41 if (name) {42 return this.headers.get(name)43 } else {44 const result: Record<string, string> = {}1 unmodified line46 result[key] = value47 }48 return result49 }43- } as InstanceType<typeof HonoRequest>['header']50+ } as InstanceType<typeof Request>['header']51 45- request.query = function (this: HonoRequest, key?: string) {52+ Request.prototype.query = function (this: Request, key?: string) {53 const url = new URL(this.url)54 if (key) {55 return url.searchParams.get(key)56 } else {2 unmodified lines59 result[key] = url.searchParams.get(key) || ''60 }61 return result62 }56- } as InstanceType<typeof HonoRequest>['query']63+ } as InstanceType<typeof Request>['query']64 58- request.queries = function (this: HonoRequest, key?: string) {65+ Request.prototype.queries = function (this: Request, key?: string) {66 const url = new URL(this.url)67 if (key) {68 return url.searchParams.getAll(key)69 } else {2 unmodified lines72 result[key] = url.searchParams.getAll(key)73 }74 return result75 }69- } as InstanceType<typeof HonoRequest>['queries']70-71- return request76+ } as InstanceType<typeof Request>['queries']77 }modified:tsconfig.json+1 added-1 removed
7 unmodified lines8 "esModuleInterop": true,9 "forceConsistentCasingInFileNames": true,10 "strict": true,11 "skipLibCheck": true,12- "strictPropertyInitialization": false,12+ "strictPropertyInitialization": true,13 "strictNullChecks": true,14 "noUnusedLocals": true,15 "noUnusedParameters": true,16 "types": [14 unmodified lines