feat: check response type (#94)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: check response type * refactor * refactor: add types
authored by Yusuke Wada · committed by GitHub · parent a72660b · Browse files · 9 files·+33 added−18 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+33 added−18 removed
- tests:+10 added−2 removed
- other:+23 added−16 removed
Provenance
- Commit
d77d890- Tree
3cac792- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
a72660b
9 files changed+33 added−18 removed
modified:examples/basic/index.js+1 added
92 unmodified lines9394959697989910092 unmodified lines// Throw Errorapp.get('/error', () => { throw Error('Error has occurred')})app.get('/type-error', () => 'return not Response instance')
// addEventListenerapp.fire()modified:src/middleware/mustache/mustache.ts+7 added-3 removed
4 unmodified lines567891011121314151617181920172122232425262724282930313217 unmodified lines505152535054555657589 unmodified lines4 unmodified linesconst DEFAULT_DOCUMENT = 'index.mustache'
type Partials = { [file: string]: string }
interface Mustache { render: (content: string, params: object, partials: Partials) => string}
type Options = { root: string}
export const mustache = (opt: Options = { root: '' }) => { const { root } = opt
return async (c: Context, next: Function) => { let Mustache: any let Mustache: Mustache try { Mustache = require('mustache') } catch { throw new Error('If you want to use Mustache Middleware, install "mustache" package first.') }
c.render = async (filename, view = {}, options?) => { c.render = async (filename, params = {}, options?) => { const path = getKVFilePath({ filename: `${filename}${EXTENSION}`, root: root, defaultDocument: DEFAULT_DOCUMENT })
const buffer = await getContentFromKVAsset(path) if (!buffer) {17 unmodified lines partialArgs[key] = bufferToString(partialBuffer) } }
const output = Mustache.render(content, view, partialArgs) const output = Mustache.render(content, params, partialArgs) return c.html(output) } await next() }9 unmodified linesmodified:src/utils/buffer.ts+2 added-2 removed
38 unmodified lines39 throw e40 }41 }42 43-export const sha256 = async (a: string): Promise<string> => {43+export const sha256 = async (a: string | object | boolean): Promise<string> => {44 if (crypto && crypto.subtle) {45 const buffer = await crypto.subtle.digest(46 {47 name: 'SHA-256',13 unmodified lines61 throw e62 }63 }64 65-export const timingSafeEqual = async (a: any, b: any) => {65+export const timingSafeEqual = async (a: string | object | boolean, b: string | object | boolean) => {66 const sa = await sha256(a)67 const sb = await sha256(b)68 return sa === sb && a === b69 }modified:src/utils/cloudflare.ts-2 removed
1-import { getMimeType } from './mime'2-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 }52 unmodified linesmodified:src/compose.ts+3 added-3 removed
122344567789101112 unmodified lines// Based on the code in the MIT licensed `koa-compose` package.export const compose = (middleware: any) => {export const compose = <T>(middleware: Function[]) => { const errors: Error[] = [] return function (context: any, next?: Function) { return function (context: T, next?: Function) { let index = -1 return dispatch(0) function dispatch(i: number): any { async function dispatch(i: number): Promise<object | void> { if (i <= index) return Promise.reject(new Error('next() called multiple times')) index = i let fn = middleware[i] if (i === middleware.length) fn = next12 unmodified linesmodified:src/hono.ts+9 added-5 removed
151 unmodified lines152 }153 }154 155 const wrappedHandler = async (context: Context, next: Function) => {156- context.res = await handler(context)156+ const res = await handler(context)157+ if (!(res instanceof Response)) {158+ throw new TypeError('response must be a instace of Response')159+ }160+ context.res = res161 await next()162 }163 164 middleware.push(wrappedHandler)165 162- const composed = compose(middleware)166+ const composed = compose<Context>(middleware)167 const c = new Context(request, { env: env, event: event, res: null })168 await composed(c)169 170 return c.res171 }172 173 async handleEvent(event: FetchEvent): Promise<Response> {170- return this.dispatch(event.request, {}, event).catch((err) => {174+ return this.dispatch(event.request, {}, event).catch((err: Error) => {175 return this.onError(err)176 })177 }178 179 async fetch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {176- return this.dispatch(request, env, event).catch((err) => {180+ return this.dispatch(request, env, event).catch((err: Error) => {181 return this.onError(err)182 })183 }184 2 unmodified lines187 event.respondWith(this.handleEvent(event))188 })189 }190 187- onError(err: any) {191+ onError(err: Error) {192 console.error(`${err}`)193 const message = 'Internal Server Error'194 return new Response(message, {195 status: 500,16 unmodified linesmodified:src/node.ts+1 added-1 removed
19 unmodified lines20 handler: T21 children: { [key: string]: Node<T> }22 middlewares: []23 24- constructor(method?: string, handler?: any, children?: { [key: string]: Node<T> }) {24+ constructor(method?: string, handler?: T, children?: { [key: string]: Node<T> }) {25 this.children = children || {}26 this.method = {}27 if (method && handler) {28 this.method[method] = handler98 unmodified linesmodified:test/compose.test.ts+1 added-1 removed
30 unmodified lines31 const response = {}32 33 it('Request', async () => {34 const c: C = { req: request, res: response }35- const composed = compose(middleware)35+ const composed = compose<C>(middleware)36 await composed(c)37 expect(c.req['log']).not.toBeNull()38 expect(c.req['log']).toBe('log message')39 })8 unmodified linesmodified:test/hono.test.ts+9 added-1 removed
255 unmodified lines256 app.get('/error', () => {257 throw 'This is Error'258 })259 260- app.use('*', async (c, next) => {260+ app.use('/error', async (c, next) => {261 try {262 await next()263 } catch (err) {264 c.res = new Response('Custom Error Message', { status: 500 })7 unmodified lines272 expect(res.status).toBe(500)273 expect(await res.text()).toBe('Custom Error Message')274 expect(res.headers.get('debug')).toBe('This is Error')275 })276+277+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment278+ // @ts-ignore279+ app.get('/text', () => 'text')280+ it('If return not Reponse object', async () => {281+ const req = new Request('https://example.com/text')282+ expect(app.dispatch(req)).rejects.toThrowError(TypeError)283+ })284 })285 286 describe('Request methods with custom middleware', () => {287 const app = new Hono()38 unmodified lines