feat(body-parse): a body parse middleware (#38)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Minghe · committed by GitHub · parent 511c0eb · Browse files · 5 files·+100 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+100 added−0 removed
- tests:+68 added−0 removed
- other:+32 added−0 removed
Provenance
- Commit
23daf7e- Tree
31d4d0e- Author
Minghe <h.minghe@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
511c0eb
5 files changed+100 added−0 removed
modified:example/basic/index.js+6 added
5 unmodified lines6789101112131462 unmodified lines77787980818283848586875 unmodified lines
// Mount Builtin Middlewareapp.use('*', Middleware.poweredBy())app.use('*', Middleware.logger())app.use('/form', Middleware.bodyParse())app.use( '/auth/*', Middleware.basicAuth({ username: 'hono',62 unmodified lines})// status codeapp.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))
app.post('/form', async (ctx) => { return ctx.json(ctx.req.parsedBody || {})//return new Response('ok /form')})
// addEventListenerapp.fire()added:src/middleware/body-parse/body-parse.test.ts+68 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import makeServiceWorkerEnv from 'service-worker-mock'import { Hono, Middleware } from '../../hono'// eslint-disable-next-line node/no-extraneous-requireconst FormData = require('form-data')
declare let global: anyObject.assign(global, makeServiceWorkerEnv())
describe('Parse Body Middleware', () => { const app = new Hono()
app.use('*', Middleware.bodyParse()) app.post('/json', async (ctx) => { return ctx.json(ctx.req.parsedBody, 200) }) app.post('/text', async (ctx) => { return ctx.text(ctx.req.parsedBody, 200) }) app.post('/form', async (ctx) => { return ctx.json(ctx.req.parsedBody, 200) })
it('POST with JSON', async () => { const payload = { message: 'hello hono' } const req = new Request('/json', { method: 'POST', body: JSON.stringify(payload), headers: new Headers({ 'Content-Type': 'application/json' }), }) const res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(await res.json()).toEqual(payload) })
it.only('POST with text', async () => { const payload = 'hello' const req = new Request('/text', { method: 'POST', body: 'hello', headers: new Headers({ 'Content-Type': 'application/text' }), }) const res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(await res.text()).toEqual(payload) })
// NOTE the service-worker-mock does not support req.formData() // so disable this test case, but verify it on live cloudflare worker, // it works, tracked by https://github.com/yusukebe/hono/issues/40 it.skip('POST with form', async () => { const formData = new FormData() formData.append('message', 'hello') const req = new Request('/form', { method: 'POST', body: formData, headers: formData.getHeaders(), }) const res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual({ message: 'hello' }) expect(await res.json()).toEqual({ message: 'hello' }) })})added:src/middleware/body-parse/body-parse.ts+23 added
1234567891011121314151617181920212223import type { Context } from '../../context'
export const bodyParse = () => { return async (ctx: Context, next: Function) => { const contentType = ctx.req.headers.get('Content-Type') || '' if (contentType.includes('application/json')) { ctx.req.parsedBody = await ctx.req.json() } else if (contentType.includes('application/text')) { ctx.req.parsedBody = await ctx.req.text() } else if (contentType.includes('text/html')) { ctx.req.parsedBody = await ctx.req.text() } else if (contentType.includes('form')) { const form: { [key: string]: string | File } = {} const data = [...(await ctx.req.formData())].reduce((acc, cur) => { acc[cur[0]] = cur[1] return acc }, form) ctx.req.parsedBody = data }
await next() }}modified:src/hono.ts+1 added
11 unmodified lines12 declare global {13 interface Request {14 params: (key: string) => string15 query: (key: string) => string | null16+ parsedBody: any17 }18 }19 20 export type Handler = (c: Context, next?: Function) => Response | Promise<Response>157 unmodified linesmodified:src/middleware.ts+2 added
12345678910111213import { defaultMiddleware } from './middleware/default'import { poweredBy } from './middleware/powered-by/powered-by'import { logger } from './middleware/logger/logger'import { basicAuth } from './middleware/basic-auth/basic-auth'import { bodyParse } from './middleware/body-parse/body-parse'
export class Middleware { static default = defaultMiddleware static poweredBy = poweredBy static logger = logger static basicAuth = basicAuth static bodyParse = bodyParse}