Support module workers syntax for Cloudflare Workers (#43)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* add fetch method and modify context * Add example of Durable Objects * Fixed export/import style * Update readme * Fixed script
authored by Yusuke Wada · committed by GitHub · parent 52b56e6 · Browse files · 18 files·+288 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+288 added−27 removed
- tests:+11 added−6 removed
- other:+277 added−21 removed
Provenance
- Commit
fceed74- Tree
ce9fbac- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
52b56e6
18 files changed+288 added−27 removed
added:example/durable-objects/src/counter.ts+37 added
12345678910111213141516171819202122232425262728293031323334353637import { Hono } from '../../../src/index'
export class Counter { value: number = 0 state: DurableObjectState app: Hono
constructor(state: DurableObjectState) { this.state = state this.state.blockConcurrencyWhile(async () => { const stored = await this.state.storage?.get<number>('value') this.value = stored || 0 })
this.app = new Hono()
this.app.get('/increment', async (c) => { const currentValue = ++this.value this.state.storage?.put('value', this.value) return c.text(currentValue.toString()) })
this.app.get('/decrement', async (c) => { const currentValue = --this.value this.state.storage?.put('value', this.value) return c.text(currentValue.toString()) })
this.app.get('/', async (c) => { return c.text(this.value.toString()) }) }
async fetch(request: Request) { return this.app.dispatch(request) }}added:example/durable-objects/src/index.ts+62 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import { Hono } from '../../../src/index'import type { Env } from '../../../src/index'
declare module '../../../src/index' { interface Env { COUNTER: DurableObjectNamespace }}
const app = new Hono()
app.get('*', async c => { const id = c.env.COUNTER.idFromName('A') const obj = c.env.COUNTER.get(id) const resp = await obj.fetch(c.req.url) const count = parseInt(await resp.text()) return c.text(`Count is ${count}`)})
export default { fetch(request: Request, env: Env, event: FetchEvent) { return app.fetch(request, env, event) },}
export class Counter { value: number = 0 state: DurableObjectState app: Hono
constructor(state: DurableObjectState) { this.state = state this.state.blockConcurrencyWhile(async () => { const stored = await this.state.storage?.get<number>('value') this.value = stored || 0 })
let currentValue = this.value
this.app = new Hono()
this.app.get('/increment', async c => { currentValue = ++this.value await this.state.storage?.put('value', this.value) return c.text(currentValue.toString()) })
this.app.get('/decrement', async c => { currentValue = --this.value await this.state.storage?.put('value', this.value) return c.text(currentValue.toString()) })
this.app.get('/', async c => { return c.text(currentValue.toString()) }) }
async fetch(request: Request) { return this.app.dispatch(request) }}added:example/durable-objects/.gitignore+5 added
1+dist2+node_modules3+worker4+package-lock.json5+yarn.lockadded:example/durable-objects/package.json+21 added
123456789101112131415161718192021{ "private": true, "name": "hono-example-durable-objects", "version": "0.0.1", "main": "dist/worker.mjs", "scripts": { "build": "webpack" }, "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)", "license": "MIT", "devDependencies": { "@cloudflare/workers-types": "^3.0", "ts-loader": "^9.2.6", "typescript": "^4.4.4", "webpack": "^5.65.0", "webpack-cli": "^4.9.1" }, "dependencies": { "hono": "*" }}No newline at end of fileadded:example/durable-objects/README.md+5 added
12345# hono-example-durable-objects
- Cloudflare Durable Objects- Module Worker Syntax- Using TypeScriptadded:example/durable-objects/tsconfig.json+28 added
12345678910111213141516171819202122232425262728{ "compilerOptions": { "outDir": "./dist", "target": "esnext", "module": "esnext", "lib": [ "esnext", "webworker" ], "declaration": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "strictPropertyInitialization": false, "strictNullChecks": false, "types": [ "@cloudflare/workers-types", ] }, "include": [ "src" ], "exclude": [ "node_modules", "dist" ]}No newline at end of fileadded:example/durable-objects/webpack.config.js+30 added
123456789101112131415161718192021222324252627282930const path = require('path')
module.exports = { entry: './src/index.ts', output: { filename: 'dist/worker.mjs', libraryTarget: 'module', path: path.join(__dirname, 'dist'), }, devtool: 'cheap-module-source-map', mode: 'development', resolve: { extensions: ['.ts', '.tsx', '.js'], }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', options: { // transpileOnly is useful to skip typescript checks occasionally: transpileOnly: true, }, }, ], }, experiments: { outputModule: true, },}added:example/durable-objects/wrangler.toml+23 added
1234567891011121314151617181920212223name = "durable-objects-counter"# type = "javascript" is required to use the `[build]` sectiontype = "javascript"account_id = ""workers_dev = trueroute = ""zone_id = ""compatibility_date = "2022-01-11"
[build]command = "yarn build"[build.upload]# The "modules" upload format is required for all projects that export a Durable Objects classformat = "modules"dir = "dist"main = "./worker.mjs"
[durable_objects]bindings = [{name = "COUNTER", class_name = "Counter"}]
[[migrations]]tag = "v1" # Should be unique for each entrynew_classes = ["CounterTs"]modified:src/middleware/basic-auth/basic-auth.test.ts+2 added-1 removed
1-import { Hono, Middleware } from '../../hono'1+import { Hono } from '../../hono'2+import { Middleware } from '../../middleware'3 4 describe('Basic Auth by Middleware', () => {5 const crypto = global.crypto6 beforeAll(() => {38 unmodified linesmodified:src/middleware/body-parse/body-parse.test.ts+2 added-1 removed
1-import { Hono, Middleware } from '../../hono'1+import { Hono } from '../../hono'2+import { Middleware } from '../../middleware'3 4 describe('Parse Body Middleware', () => {5 const app = new Hono()6 56 unmodified linesmodified:src/middleware/logger/logger.test.ts+2 added-1 removed
1-import { Hono, Middleware } from '../../hono'1+import { Hono } from '../../hono'2+import { Middleware } from '../../middleware'3 4 describe('Logger by Middleware', () => {5 const app = new Hono()6 28 unmodified linesmodified:src/middleware/powered-by/powered-by.test.ts+2 added-1 removed
1-import { Hono, Middleware } from '../../hono'1+import { Hono } from '../../hono'2+import { Middleware } from '../../middleware'3 4 describe('Powered by Middleware', () => {5 const app = new Hono()6 11 unmodified linesmodified:src/context.ts+10 added-2 removed
1 import { isAbsoluteURL } from './util'2 3 type Headers = { [key: string]: string }4 5+export interface Env {}6+7 export class Context {8 req: Request9 res: Response10+ env: Env11+ event: FetchEvent12 9- constructor(req: Request, res: Response) {13+ constructor(req: Request, opts?: { res: Response; env: Env; event: FetchEvent }) {14 this.req = req15+ if (opts) {11- this.res = res16+ this.res = opts.res17+ this.env = opts.env18+ this.event = opts.event19+ }20 }21 22 newResponse(body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response {23 return new Response(body, init)59 unmodified linesmodified:src/hono.ts+12 added-10 removed
2 unmodified lines3 import { compose } from './compose'4 import { getPathFromURL } from './util'5 import { Middleware } from './middleware'6 import { Context } from './context'7+import type { Env } from './context'8 8-export { Middleware }9-9 const METHOD_NAME_OF_ALL = 'ALL'10 11 declare global {12 interface Request {3 unmodified lines16 }17 }18 19 export type Handler = (c: Context, next?: Function) => Response | Promise<Response>21-export type MiddlwareHandler = (c: Context, next: Function) => Promise<void>20+export type MiddlewareHandler = (c: Context, next: Function) => Promise<void>21 22 export class Router<T> {23 node: Node<T>24 11 unmodified lines36 }37 38 export class Hono {39 router: Router<Handler[]>41- middlewareRouters: Router<MiddlwareHandler>[]40+ middlewareRouters: Router<MiddlewareHandler>[]41 tempPath: string42 43 constructor() {44 this.router = new Router()48 unmodified lines93 this.tempPath = path94 return this95 }96 98- use(path: string, middleware: MiddlwareHandler): void {97+ use(path: string, middleware: MiddlewareHandler): void {98 if (middleware.constructor.name !== 'AsyncFunction') {99 throw new TypeError('middleware must be a async function!')100 }101 103- const router = new Router<MiddlwareHandler>()102+ const router = new Router<MiddlewareHandler>()103 router.add(METHOD_NAME_OF_ALL, path, middleware)104 this.middlewareRouters.push(router)105 }106 13 unmodified lines120 async matchRoute(method: string, path: string): Promise<Result<Handler[]>> {121 return this.router.match(method, path)122 }123 125- async dispatch(request: Request, response?: Response) {124+ async dispatch(request: Request, env?: Env, event?: FetchEvent) {125 const [method, path] = [request.method, getPathFromURL(request.url)]126 127 const result = await this.matchRoute(method, path)128 23 unmodified lines152 middleware.push(Middleware.default)153 middleware.push(wrappedHandler)154 155 const composed = compose(middleware)157- const c = new Context(request, response)158-156+ const c = new Context(request, { env: env, event: event, res: null })157 await composed(c)158 159 return c.res160 }161 162 async handleEvent(event: FetchEvent): Promise<Response> {165- return this.dispatch(event.request)163+ return this.dispatch(event.request, {}, event)164 }165 166+ async fetch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {167+ return this.dispatch(request, env, event)168+ }169+170 fire() {171 addEventListener('fetch', (event: FetchEvent): void => {172 event.respondWith(this.handleEvent(event))173 })6 unmodified linesmodified:src/index.ts+4 added-1 removed
1-export { Hono, Middleware, Handler, MiddlwareHandler } from './hono'1+export { Hono } from './hono'2+export type { Handler, MiddlewareHandler } from './hono'3+export { Middleware } from './middleware'4 export { Context } from './context'5+export type { Env } from './context'modified:test/context.test.ts+1 added-1 removed
1 import { Context } from '../src/context'2 3 describe('Context', () => {4 const req = new Request('http://localhost/')5- const c = new Context(req, new Response())5+ const c = new Context(req)6 7 it('c.text', async () => {8 const res = c.text('text in c', 201, { 'X-Custom': 'Message' })9 expect(res.status).toBe(201)32 unmodified linesmodified:test/middleware.test.ts+2 added-1 removed
1-import { Hono, Middleware } from '../src/hono'1+import { Hono } from '../src/hono'2+import { Middleware } from '../src/middleware'3 4 describe('Builtin Middleware', () => {5 const app = new Hono()6 11 unmodified linesmodified:README.md+40 added-8 removed
1 # Hono2 3-Hono [炎] - Ultrafast web framework for Cloudflare Workers.3+Hono[炎] - _**means flame🔥 in Japanese**_ - is small, simple, and ultrafast web flamework for a Service Workers API based serverless such as Cloudflare Workers and Fastly Compute@Edge.4 5 ```js6 import { Hono } from 'hono'7 const app = new Hono()2 unmodified lines10 11 app.fire()12 ```13 14-Hono[炎] - _**means flame🔥 in Japanese**_ - is small, simple, and ultrafast web flamework for a Service Workers API based serverless such as **Cloudflare Workers** and **Fastly Compute@Edge**. Hono does not depend on any npm packages. But, Hono has a router, context object, and middleware including the builtins. Easy to make a web application.15-14 ## Features15 18-- **Fast** - the router is implemented with Trie-Tree structure.19-- **Tiny** - zero dependencies, using Web standard API.20-- **Flexible** - you can make your own middleware.21-- **Easy** - simple API, builtin middleware, and written in TypeScript.22-- **Optimized** - for Cloudflare Workers or Fastly Compute@Edge.16+- **Ultra Fast** - the router is implemented with Trie-Tree structure.17+- **Zero dependencies** - using only Web standard API.18+- **Middleware** - builtin middleware, and you can make your own middleware.19+- **Optimized** - for Cloudflare Workers.20 21 ## Benchmark22 23 **Hono is fastest** compared to other routers for Cloudflare Workers.35 unmodified lines59 - app.**all**(path, handler)60 - app.**route**(path)61 - app.**use**(path, middleware)62 - app.**fire**()63+- app.**fetch**(request, env, event)64 65 ## Routing66 67 ### Basic167 unmodified lines235 c.res.headers.append('X-Debug', 'Debug message')236 })237 ```238 239+### c.event240+241+```js242+// FetchEvent objest243+app.use('*', async (c, next) => {244+ c.event.waitUntil(245+ ...246+ )247+ await next()248+})249+```250+251+### c.env252+253+```js254+// Environment object for Cloudflare Workers255+app.get('*', async c => {256+ const counter = c.env.COUNTER257+ ...258+})259+```260+261 ### c.text()262 263 Render text as `Content-Type:text/plain`:264 41 unmodified lines306 event.respondWith(this.handleEvent(event))307 })308 ```309 310+## fetch311+312+`app.fetch()` is for Cloudflare Module Worker syntax.313+314+```js315+export default {316+ fetch(request: Request, env: Env, event: FetchEvent) {317+ return app.fetch(request, env, event)318+ },319+}320+```321+322 ## Cloudflare Workers with Hono323 324 Using `wrangler` or `miniflare`, you can develop the application locally and publish it with few commands.325 95 unmodified lines