feat: add `serve-static` middlware for deno (#339)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: add `serve-static` middlware for deno * make `getFilePath` into utils * ignore deno ts files
authored by Yusuke Wada · committed by GitHub · parent 6030c05 · Browse files · 15 files·+185 added−73 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+185 added−73 removed
- tests:+20 added−17 removed
- other:+165 added−56 removed
Provenance
- Commit
1cdd71f- Tree
0c3a7f4- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
6030c05
15 files changed+185 added−73 removed
added:deno_dist/deno/serve-static.ts+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243import type { Context } from '../context.ts'import type { Next } from '../hono.ts'import { getFilePath } from '../utils/filepath.ts'import { getMimeType } from '../utils/mime.ts'
export type ServeStaticOptions = { root?: string path?: string}
const DEFAULT_DOCUMENT = 'index.html'
export const serveStatic = (options: ServeStaticOptions = { root: '' }) => { return async (c: Context, next: Next): Promise<Response | undefined> => { // Do nothing if Response is already set if (c.res && c.finalized) { await next() }
const url = new URL(c.req.url)
let path = getFilePath({ filename: options.path ?? url.pathname, root: options.root, defaultDocument: DEFAULT_DOCUMENT, })
path = `./${path}` const content = await Deno.readFile(path) if (content) { const mimeType = getMimeType(path) if (mimeType) { c.header('Content-Type', mimeType) } // Return Response object return c.body(content) } else { console.warn(`Static file: ${path} is not found`) await next() } return }}added:deno_dist/utils/filepath.ts+31 added
12345678910111213141516171819202122232425262728293031type FilePathOptions = { filename: string root?: string defaultDocument?: string}
export const getFilePath = (options: FilePathOptions): string => { let filename = options.filename let root = options.root || '' const defaultDocument = options.defaultDocument || 'index.html'
if (filename.endsWith('/')) { // /top/ => /top/index.html filename = filename.concat(defaultDocument) } else if (!filename.match(/\.[a-zA-Z0-9]+$/)) { // /top => /top/index.html filename = filename.concat('/' + defaultDocument) }
// /foo.html => foo.html filename = filename.replace(/^\.?\//, '')
// assets/ => assets root = root.replace(/\/$/, '')
// ./assets/foo.html => assets/foo.html let path = root ? root + '/' + filename : filename path = path.replace(/^\.?\//, '')
return path}modified:deno_dist/mod.ts+1 added
48 unmodified lines495051525348 unmodified linesexport { jwt } from './middleware/jwt/index.ts'export { logger } from './middleware/logger/index.ts'export { poweredBy } from './middleware/powered-by/index.ts'export { prettyJSON } from './middleware/pretty-json/index.ts'export { serveStatic } from './deno/serve-static.ts'modified:deno_dist/README.md+2 added-9 removed
761 unmodified lines762 763 ```tsx764 /** @jsx jsx */765 import { serve } from 'https://deno.land/std@0.146.0/http/server.ts'766-import { Hono, logger, poweredBy, basicAuth, jsx } from 'https://deno.land/x/hono/mod.ts'766+import { Hono, logger, poweredBy, serveStatic, jsx } from 'https://deno.land/x/hono/mod.ts'767 768 const app = new Hono()769 770 app.use('*', logger(), poweredBy())771-app.get(772- '/auth/*',773- basicAuth({774- username: 'deno',775- password: 'iscool',776- })777-)771 772+app.get('/favicon.ico', serveStatic({ path: './public/favicon.ico' }))773 app.get('/', (c) => {774 return c.html(<h1>Hello Deno!</h1>)775 })782-app.get('/auth/abc', (c) => c.text('You are authorized'))776 777 serve(app.fire())778 ```779 33 unmodified linesadded:src/deno/serve-static.ts+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243import type { Context } from '../context'import type { Next } from '../hono'import { getFilePath } from '../utils/filepath'import { getMimeType } from '../utils/mime'
export type ServeStaticOptions = { root?: string path?: string}
const DEFAULT_DOCUMENT = 'index.html'
export const serveStatic = (options: ServeStaticOptions = { root: '' }) => { return async (c: Context, next: Next): Promise<Response | undefined> => { // Do nothing if Response is already set if (c.res && c.finalized) { await next() }
const url = new URL(c.req.url)
let path = getFilePath({ filename: options.path ?? url.pathname, root: options.root, defaultDocument: DEFAULT_DOCUMENT, })
path = `./${path}` const content = await Deno.readFile(path) if (content) { const mimeType = getMimeType(path) if (mimeType) { c.header('Content-Type', mimeType) } // Return Response object return c.body(content) } else { console.warn(`Static file: ${path} is not found`) await next() } return }}modified:src/middleware/mustache/mustache.ts+4 added-3 removed
1234566789101119 unmodified lines3132333434353637383913 unmodified lines5354555656575859606115 unmodified linesimport Mustache from 'mustache'import type { Context } from '../../context'import type { Next } from '../../hono'import { bufferToString } from '../../utils/buffer'import type { KVAssetOptions } from '../../utils/cloudflare'import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare'import { getContentFromKVAsset } from '../../utils/cloudflare'import { getFilePath } from '../../utils/filepath'
const EXTENSION = '.mustache'const DEFAULT_DOCUMENT = 'index.mustache'
19 unmodified lines const { root } = init
return async (c: Context, next: Next) => { c.render = async (filename, params = {}, options?): Promise<Response> => { const path = getKVFilePath({ const path = getFilePath({ filename: `${filename}${EXTENSION}`, root: root, defaultDocument: DEFAULT_DOCUMENT, })13 unmodified lines
if (options) { const partials = options as Partials for (const key of Object.keys(partials)) { const partialPath = getKVFilePath({ const partialPath = getFilePath({ filename: `${partials[key]}${EXTENSION}`, root: root, defaultDocument: DEFAULT_DOCUMENT, })15 unmodified linesmodified:src/middleware/serve-static/serve-static.ts+3 added-2 removed
1 import type { Context, Env } from '../../context'2 import type { Handler, Next } from '../../hono'3-import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare'3+import { getContentFromKVAsset } from '../../utils/cloudflare'4+import { getFilePath } from '../../utils/filepath'5 import { getMimeType } from '../../utils/mime'6 7 export type ServeStaticOptions = {8 root?: string13 unmodified lines22 }23 24 const url = new URL(c.req.url)25 25- const path = getKVFilePath({26+ const path = getFilePath({27 filename: options.path ?? url.pathname,28 root: options.root,29 defaultDocument: DEFAULT_DOCUMENT,30 })19 unmodified linesmodified:src/utils/cloudflare.test.ts+1 added-17 removed
1-import { getContentFromKVAsset, getKVFilePath } from './cloudflare'1+import { getContentFromKVAsset } from './cloudflare'2 3 // Mock4 const store: { [key: string]: string } = {5 'index.abcdef.html': 'This is index',23 unmodified lines29 content = await getContentFromKVAsset('assets/static/plain.txt')30 expect(content).not.toBeUndefined()31 expect(content).toBe('Asset text')32 })33-34- it('getKVFilePath', async () => {35- expect(getKVFilePath({ filename: 'foo' })).toBe('foo/index.html')36- expect(getKVFilePath({ filename: 'foo.txt' })).toBe('foo.txt')37-38- expect(getKVFilePath({ filename: 'foo', root: 'bar' })).toBe('bar/foo/index.html')39- expect(getKVFilePath({ filename: 'foo.txt', root: 'bar' })).toBe('bar/foo.txt')40-41- expect(getKVFilePath({ filename: 'foo', defaultDocument: 'index.txt' })).toBe('foo/index.txt')42- expect(getKVFilePath({ filename: 'foo', root: 'bar', defaultDocument: 'index.txt' })).toBe(43- 'bar/foo/index.txt'44- )45-46- expect(getKVFilePath({ filename: './foo' })).toBe('foo/index.html')47- expect(getKVFilePath({ filename: 'foo', root: './bar' })).toBe('bar/foo/index.html')48- })33 })modified:src/utils/cloudflare.ts-32 removed
43 unmodified lines44 content = content as ArrayBuffer45 }46 return content47 }48-49-type FilePathOptions = {50- filename: string51- root?: string52- defaultDocument?: string53-}54-55-export const getKVFilePath = (options: FilePathOptions): string => {56- let filename = options.filename57- let root = options.root || ''58- const defaultDocument = options.defaultDocument || 'index.html'59-60- if (filename.endsWith('/')) {61- // /top/ => /top/index.html62- filename = filename.concat(defaultDocument)63- } else if (!filename.match(/\.[a-zA-Z0-9]+$/)) {64- // /top => /top/index.html65- filename = filename.concat('/' + defaultDocument)66- }67-68- // /foo.html => foo.html69- filename = filename.replace(/^\.?\//, '')70-71- // assets/ => assets72- root = root.replace(/\/$/, '')73-74- // ./assets/foo.html => assets/foo.html75- let path = root ? root + '/' + filename : filename76- path = path.replace(/^\.?\//, '')77-78- return path79-}added:src/utils/filepath.test.ts+19 added
1+import { getFilePath } from './filepath'2+3+describe('getFilePath', () => {4+ it('Should return file path correctly', async () => {5+ expect(getFilePath({ filename: 'foo' })).toBe('foo/index.html')6+ expect(getFilePath({ filename: 'foo.txt' })).toBe('foo.txt')7+8+ expect(getFilePath({ filename: 'foo', root: 'bar' })).toBe('bar/foo/index.html')9+ expect(getFilePath({ filename: 'foo.txt', root: 'bar' })).toBe('bar/foo.txt')10+11+ expect(getFilePath({ filename: 'foo', defaultDocument: 'index.txt' })).toBe('foo/index.txt')12+ expect(getFilePath({ filename: 'foo', root: 'bar', defaultDocument: 'index.txt' })).toBe(13+ 'bar/foo/index.txt'14+ )15+16+ expect(getFilePath({ filename: './foo' })).toBe('foo/index.html')17+ expect(getFilePath({ filename: 'foo', root: './bar' })).toBe('bar/foo/index.html')18+ })19+})added:src/utils/filepath.ts+31 added
1+type FilePathOptions = {2+ filename: string3+ root?: string4+ defaultDocument?: string5+}6+7+export const getFilePath = (options: FilePathOptions): string => {8+ let filename = options.filename9+ let root = options.root || ''10+ const defaultDocument = options.defaultDocument || 'index.html'11+12+ if (filename.endsWith('/')) {13+ // /top/ => /top/index.html14+ filename = filename.concat(defaultDocument)15+ } else if (!filename.match(/\.[a-zA-Z0-9]+$/)) {16+ // /top => /top/index.html17+ filename = filename.concat('/' + defaultDocument)18+ }19+20+ // /foo.html => foo.html21+ filename = filename.replace(/^\.?\//, '')22+23+ // assets/ => assets24+ root = root.replace(/\/$/, '')25+26+ // ./assets/foo.html => assets/foo.html27+ let path = root ? root + '/' + filename : filename28+ path = path.replace(/^\.?\//, '')29+30+ return path31+}modified:src/mod.ts+1 added
48 unmodified lines49 export { jwt } from './middleware/jwt'50 export { logger } from './middleware/logger'51 export { poweredBy } from './middleware/powered-by'52 export { prettyJSON } from './middleware/pretty-json'53+export { serveStatic } from './deno/serve-static'modified:README.md+2 added-9 removed
761 unmodified lines762 763 ```tsx764 /** @jsx jsx */765 import { serve } from 'https://deno.land/std@0.146.0/http/server.ts'766-import { Hono, logger, poweredBy, basicAuth, jsx } from 'https://deno.land/x/hono/mod.ts'766+import { Hono, logger, poweredBy, serveStatic, jsx } from 'https://deno.land/x/hono/mod.ts'767 768 const app = new Hono()769 770 app.use('*', logger(), poweredBy())771-app.get(772- '/auth/*',773- basicAuth({774- username: 'deno',775- password: 'iscool',776- })777-)771 772+app.get('/favicon.ico', serveStatic({ path: './public/favicon.ico' }))773 app.get('/', (c) => {774 return c.html(<h1>Hello Deno!</h1>)775 })782-app.get('/auth/abc', (c) => c.text('You are authorized'))776 777 serve(app.fire())778 ```779 33 unmodified linesmodified:tsconfig.build.esm.json+3 added-1 removed
9 unmodified lines10 "src/**/*.mts"11 ],12 "exclude": [13 "src/**/*.ts",14- "src/**/*.test.ts"14+ "src/**/*.test.ts",15+ "src/mod.ts",16+ "src/deno/**/*.ts",17 ]18 }modified:tsconfig.build.json+1 added
3 unmodified lines4 "src/**/*.ts"5 ],6 "exclude": [7 "src/mod.ts",8+ "src/deno/**/*.ts",9 "src/**/*.test.ts"10 ]11 }