feat: mustache middleware supports Module Worker mode (#252)
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 923a30e · Browse files · 7 files·+184 added−128 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+184 added−128 removed
- tests:+73 added−58 removed
- other:+111 added−70 removed
Provenance
- Commit
56703c6- Tree
a75b574- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
923a30e
7 files changed+184 added−128 removed
deleted:src/middleware/mustache/index.test.ts-58 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import { Hono } from '../../hono'import { mustache } from '.'
// Mockconst store: { [key: string]: string } = { 'index.abcdef.mustache': '{{> header}}Title: {{ title }}{{> footer}}', 'header.abcdef.mustache': '<html><body>', 'footer.abcdef.mustache': '</body></html>', 'view/index.abcdef.mustache': '<h1>With Root</h1>',}const manifest = JSON.stringify({ 'index.mustache': 'index.abcdef.mustache', 'header.mustache': 'header.abcdef.mustache', 'footer.mustache': 'footer.abcdef.mustache', 'view/index.mustache': 'view/index.abcdef.mustache',})
Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })Object.assign(global, { __STATIC_CONTENT: { get: (path: string) => { return store[path] }, },})
describe('Mustache by Middleware', () => { const app = new Hono()
app.use('/foo', mustache()) app.get('/foo', (c) => { return c.render( 'index', { title: 'Hono!' }, { header: 'header', footer: 'footer', } ) })
app.use('/bar', mustache({ root: 'view' })) app.get('/bar', (c) => { return c.render('index') })
it('Mustache template rendering', async () => { const res = await app.request('http://localhost/foo') expect(res.status).toBe(200) expect(await res.text()).toBe('<html><body>Title: Hono!</body></html>') })
it('Mustache template rendering with root', async () => { const res = await app.request('http://localhost/bar') expect(res.status).toBe(200) expect(await res.text()).toBe('<h1>With Root</h1>') })})modified:src/middleware/mustache/index.ts+1 added-67 removed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566671import type { Context } from '../../context'import type { Next } from '../../hono'import { bufferToString } from '../../utils/buffer'import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare'
const EXTENSION = '.mustache'const DEFAULT_DOCUMENT = 'index.mustache'
type Partials = Record<string, string>
interface Mustache { render: (content: string, params: object, partials: Partials) => string}
type Init = { root: string}
export const mustache = (init: Init = { root: '' }) => { const { root } = init
return async (c: Context, next: Next) => { 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, params = {}, options?) => { const path = getKVFilePath({ filename: `${filename}${EXTENSION}`, root: root, defaultDocument: DEFAULT_DOCUMENT, })
const buffer = await getContentFromKVAsset(path) if (!buffer) { throw new Error(`Template "${path}" is not found or blank.`) } const content = bufferToString(buffer)
const partialArgs: Record<string, string> = {}
if (options) { const partials = options as Partials for (const key of Object.keys(partials)) { const partialPath = getKVFilePath({ filename: `${partials[key]}${EXTENSION}`, root: root, defaultDocument: DEFAULT_DOCUMENT, }) const partialBuffer = await getContentFromKVAsset(partialPath) if (!partialBuffer) { throw new Error(`Partial Template "${partialPath}" is not found or blank.`) } partialArgs[key] = bufferToString(partialBuffer) } }
const output = Mustache.render(content, params, partialArgs) return c.html(output) }
await next() }}export { mustache } from './mustache'added:src/middleware/mustache/module.mts+15 added
123456789101112131415// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignore// For ES module modeimport manifest from '__STATIC_CONTENT_MANIFEST'import type { MustacheOptions } from './mustache'import { mustache } from './mustache'
const module = (options: MustacheOptions = { root: '' }) => { return mustache({ root: options.root, manifest: options.manifest ? options.manifest : manifest, })}
export { module as mustache }added:src/middleware/mustache/mustache.test.ts+73 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import { Hono } from '../../hono'import { mustache } from './mustache'
// Mockconst store: { [key: string]: string } = { 'index.abcdef.mustache': '{{> header}}Title: {{ title }}{{> footer}}', 'header.abcdef.mustache': '<html><body>', 'footer.abcdef.mustache': '</body></html>', 'view/index.abcdef.mustache': '<h1>With Root</h1>', 'view/options.abcdef.mustache': '<h1>With Options</h1>',}const manifest = JSON.stringify({ 'index.mustache': 'index.abcdef.mustache', 'header.mustache': 'header.abcdef.mustache', 'footer.mustache': 'footer.abcdef.mustache', 'view/index.mustache': 'view/index.abcdef.mustache',})
Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })Object.assign(global, { __STATIC_CONTENT: { get: (path: string) => { return store[path] }, },})
describe('Mustache by Middleware', () => { const app = new Hono()
app.use('/foo', mustache()) app.get('/foo', (c) => { return c.render( 'index', { title: 'Hono!' }, { header: 'header', footer: 'footer', } ) })
app.use('/bar', mustache({ root: 'view' })) app.get('/bar', (c) => { return c.render('index') })
const manifest = { 'view/options.mustache': 'view/options.abcdef.mustache', } app.use('/options', mustache({ root: 'view', manifest: manifest })) app.get('/options', (c) => { return c.render('options') })
it('Mustache template rendering', async () => { const res = await app.request('http://localhost/foo') expect(res.status).toBe(200) expect(await res.text()).toBe('<html><body>Title: Hono!</body></html>') })
it('Mustache template rendering with root', async () => { const res = await app.request('http://localhost/bar') expect(res.status).toBe(200) expect(await res.text()).toBe('<h1>With Root</h1>') })
it('Mustache template rendering with options', async () => { const res = await app.request('http://localhost/options') expect(res.status).toBe(200) expect(await res.text()).toBe('<h1>With Options</h1>') })})added:src/middleware/mustache/mustache.ts+75 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import type { Context } from '../../context'import type { Handler, Next } from '../../hono'import { bufferToString } from '../../utils/buffer'import type { KVAssetOptions } from '../../utils/cloudflare'import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare'
const EXTENSION = '.mustache'const DEFAULT_DOCUMENT = 'index.mustache'
type Partials = Record<string, string>
interface Mustache { render: (content: string, params: object, partials: Partials) => string}
export type MustacheOptions = { root: string manifest?: object | string namespace?: KVNamespace}
export const mustache = (init: MustacheOptions = { root: '' }): Handler => { const { root } = init
return async (c: Context, next: Next) => { 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, params = {}, options?) => { const path = getKVFilePath({ filename: `${filename}${EXTENSION}`, root: root, defaultDocument: DEFAULT_DOCUMENT, })
const kvAssetOptions: KVAssetOptions = { manifest: init.manifest, namespace: init.namespace ? init.namespace : c.env ? c.env.__STATIC_CONTENT : undefined, }
const buffer = await getContentFromKVAsset(path, kvAssetOptions) if (!buffer) { throw new Error(`Template "${path}" is not found or blank.`) } const content = bufferToString(buffer)
const partialArgs: Record<string, string> = {}
if (options) { const partials = options as Partials for (const key of Object.keys(partials)) { const partialPath = getKVFilePath({ filename: `${partials[key]}${EXTENSION}`, root: root, defaultDocument: DEFAULT_DOCUMENT, }) const partialBuffer = await getContentFromKVAsset(partialPath, kvAssetOptions) if (!partialBuffer) { throw new Error(`Partial Template "${partialPath}" is not found or blank.`) } partialArgs[key] = bufferToString(partialBuffer) } }
const output = Mustache.render(content, params, partialArgs) return c.html(output) }
await next() }}modified:src/middleware/mustache/README.md+15 added-2 removed
16 unmodified lines17 ```18 19 ## Usage20 21-index.js:21+index.ts:22 23-```js23+```ts24 import { Hono } from 'hono'25 import { mustache } from 'hono/mustache'26 27 const app = new Hono()10 unmodified lines38 39 app.fire()40 ```41 42+In Module Worker mode:43+44+```ts45+import { Hono } from 'hono'46+import { mustache } from 'hono/mustache.module' // <---47+48+const app = new Hono()49+app.use('*', mustache())50+// ...51+52+export default app53+```54+55 index.mustache:56 57 ```mustache58 {{> header}}26 unmodified linesmodified:package.json+5 added-1 removed
24 unmodified lines25 "./graphql-server": "./dist/middleware/graphql-server/index.js",26 "./jwt": "./dist/middleware/jwt/index.js",27 "./logger": "./dist/middleware/logger/index.js",28 "./mustache": "./dist/middleware/mustache/index.js",29+ "./mustache.module": "./dist/middleware/mustache/module.mjs",30 "./powered-by": "./dist/middleware/powered-by/index.js",31 "./pretty-json": "./dist/middleware/pretty-json/index.js",32 "./serve-static": "./dist/middleware/serve-static/index.js",33 "./serve-static.module": "./dist/middleware/serve-static/module.mjs",30 unmodified lines64 ],65 "mustache": [66 "./dist/middleware/mustache"67 ],68+ "mustache.module": [69+ "./dist/middleware/mustache/module.d.mts"70+ ],71 "powered-by": [72 "./dist/middleware/powered-by"73 ],74 "pretty-json": [2 unmodified lines77 "serve-static": [78 "./dist/middleware/serve-static/index.d.ts"79 ],80 "serve-static.module": [77- "./dist/middleware/serve-static/module.d.ts"81+ "./dist/middleware/serve-static/module.d.mts"82 ],83 "router/trie-router": [84 "./dist/router/trie-router/router.d.ts"85 ],62 unmodified lines