feat: etag middleware (#119)
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 bea8aef · Browse files · 6 files·+166 added−17 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+166 added−17 removed
- tests:+107 added−0 removed
- other:+59 added−17 removed
Provenance
- Commit
7c454ee- Tree
ab11058- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
bea8aef
6 files changed+166 added−17 removed
modified:examples/basic/index.js+4 added
123456789106 unmodified lines17181920212223242543 unmodified lines6970717273747576777837 unmodified linesimport { Hono } from '../../dist'import { poweredBy } from '../../src/middleware/powered-by/powered-by'import { logger } from '../../src/middleware/logger/logger'import { bodyParse } from '../../src/middleware/body-parse/body-parse'import { basicAuth } from '../../src/middleware/basic-auth/basic-auth'import { etag } from '../../src/middleware/etag/etag'
const app = new Hono()
// Mount Builtin Middleware6 unmodified lines username: 'hono', password: 'acoolproject', }))app.use('/etag/*', etag())
// Custom Middleware// Add Custom Headerapp.use('/hello/*', async (c, next) => {43 unmodified lines// Redirectapp.get('/redirect', (c) => c.redirect('/'))// Authentication requiredapp.get('/auth/*', (c) => c.text('You are authorized'))// ETagapp.get('/etag/cached', (c) => c.text('Is this cached?'))
// Asyncapp.get('/fetch-url', async (c) => { const response = await fetch('https://example.com/')37 unmodified linesmodified:src/middleware/body-parse/body-parse.ts+2 added-17 removed
12345567869101112131415161718192021789import { parseBody } from '../../utils/body'import 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() ctx.req.parsedBody = await parseBody(ctx.req) } 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: Record<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() }}added:src/middleware/etag/etag.test.ts+60 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import { Hono } from '../../hono'import { etag } from './etag'
describe('Etag Middleware', () => { const app = new Hono()
app.use('/etag/*', etag()) app.get('/etag/abc', (c) => { return c.text('Hono is cool') }) app.get('/etag/def', (c) => { return c.json({ message: 'Hono is cool' }) })
app.use('/etag-weak/*', etag({ weak: true })) app.get('/etag-weak/abc', (c) => { return c.text('Hono is cool') })
it('should return etag header', async () => { let req = new Request('http://localhost/etag/abc') let res = await app.dispatch(req)
expect(res.headers.get('ETag')).not.toBeFalsy() expect(res.headers.get('ETag')).toBe('"4e32298b1cb4edc595237405e5b696e105c2399a"')
req = new Request('http://localhost/etag/def') res = await app.dispatch(req)
expect(res.headers.get('ETag')).not.toBeFalsy() expect(res.headers.get('ETag')).toBe('"c1d44ff03aff1372856c281854f454e2e1d15b7c"') })
it('should return etag header - weak', async () => { const req = new Request('http://localhost/etag-weak/abc') const res = await app.dispatch(req)
expect(res.headers.get('ETag')).not.toBeFalsy() expect(res.headers.get('ETag')).toBe('W/"4e32298b1cb4edc595237405e5b696e105c2399a"') })
it('should return 304 response', async () => { let req = new Request('http://localhost/etag/abc') let res = await app.dispatch(req)
expect(res.status).toBe(200) expect(res.headers.get('ETag')).not.toBeFalsy() const etag = res.headers.get('Etag')
req = new Request('http://localhost/etag/abc', { headers: { 'If-None-Match': etag, }, }) res = await app.dispatch(req)
expect(res.status).toBe(304) expect(await res.text()).toBe('') })})added:src/middleware/etag/etag.ts+33 added
123456789101112131415161718192021222324252627282930313233import { sha1 } from '../../utils/crypto'import { parseBody } from '../../utils/body'import type { Context } from '../../context'
type ETagOptions = { weak: boolean}
export const etag = (options: ETagOptions = { weak: false }) => { return async (c: Context, next: Function) => { const ifNoneMatch = c.req.header('If-None-Match') || c.req.header('if-none-match')
await next()
const clone = c.res.clone() const body = await parseBody(c.res) const hash = await sha1(body)
const etag = options.weak ? `W/"${hash}"` : `"${hash}"`
if (ifNoneMatch && ifNoneMatch === etag) { await clone.blob() // Force using body c.res = new Response(null, { status: 304, statusText: 'Not Modified', }) c.res.headers.delete('Content-Length') } else { c.res = new Response(clone.body, clone) c.res.headers.append('ETag', etag) } }}added:src/utils/body.test.ts+47 added
1+import { parseBody } from './body'2+3+describe('Parse Body Middleware', () => {4+ it('should parse JSON', async () => {5+ const payload = { message: 'hello hono' }6+ const req = new Request('http://localhost/json', {7+ method: 'POST',8+ body: JSON.stringify(payload),9+ headers: new Headers({ 'Content-Type': 'application/json' }),10+ })11+ expect(await parseBody(req)).toEqual(payload)12+ })13+14+ it('should parse Text', async () => {15+ const payload = 'hello'16+ const req = new Request('http://localhost/text', {17+ method: 'POST',18+ body: 'hello',19+ headers: new Headers({ 'Content-Type': 'application/text' }),20+ })21+ expect(await parseBody(req)).toEqual(payload)22+ })23+24+ it('should parse Form', async () => {25+ const formData = new URLSearchParams()26+ formData.append('message', 'hello')27+ const req = new Request('https://localhost/form', {28+ method: 'POST',29+ body: formData,30+ headers: {31+ 'Content-Type': 'application/x-www-form-urlencoded',32+ },33+ })34+ expect(await parseBody(req)).toEqual({ message: 'hello' })35+ })36+37+ it('should parse Reponse body ', async () => {38+ const payload = 'hello'39+ const res = new Response(payload, {40+ headers: {41+ 'Content-Type': 'text/plain',42+ },43+ })44+ console.log(res.headers.get('Content-Type'))45+ expect(await parseBody(res)).toEqual(payload)46+ })47+})added:src/utils/body.ts+20 added
1234567891011121314151617181920export const parseBody = async ( r: Request | Response): Promise<string | object | Record<string, string | File>> => { const contentType = r.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) { return await r.json() } else if (contentType.includes('application/text')) { return r.text() } else if (contentType.startsWith('text')) { return r.text() } else if (contentType.includes('form')) { const form: Record<string, string | File> = {} const data = [...(await r.formData())].reduce((acc, cur) => { acc[cur[0]] = cur[1] return acc }, form) return data }}