Skip to content
Myr

chore: move examples to github.com/honojs/examples (#181)

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 feebd88 · Browse files · 52 files+2 added−1030 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

52 files+2 added−1030 removed

  • tests:+0 added−79 removed
  • other:+2 added−951 removed

52 files+2 added−1030 removed

deleted:examples/basic/.gitignore-5 removed
1dist2node_modules3worker4package-lock.json5yarn.lock
deleted:examples/basic/index.js-115 removed
1import { Hono } from 'hono'2import { basicAuth } from 'hono/basic-auth'3import { bodyParse } from 'hono/body-parse'4import { etag } from 'hono/etag'5import { logger } from 'hono/logger'6import { poweredBy } from 'hono/powered-by'78const app = new Hono()910// Mount Builtin Middleware11app.use('*', poweredBy())12app.use('*', logger())13app.use('/form', bodyParse())14app.use(15 '/auth/*',16 basicAuth({17 username: 'hono',18 password: 'acoolproject',19 })20)21app.use('/etag/*', etag())2223// Custom Middleware24// Add Custom Header25app.use('/hello/*', async (c, next) => {26 await next()27 c.header('X-message', 'This is addHeader middleware!')28})2930// Add X-Response-Time header31app.use('*', async (c, next) => {32 const start = Date.now()33 await next()34 const ms = Date.now() - start35 c.header('X-Response-Time', `${ms}ms`)36})3738// Custom Not Found Message39app.notFound((c) => {40 return c.text('Custom 404 Not Found', 404)41})4243// Error handling44app.onError((err, c) => {45 console.error(`${err}`)46 return c.text('Custom Error Message', 500)47})4849// Routing50app.get('/', (c) => c.text('Hono!!'))51// Use Response object directly52app.get('/hello', () => new Response('This is /hello'))5354// Named parameter55app.get('/entry/:id', (c) => {56 const id = c.req.param('id')57 return c.text(`Your ID is ${id}`)58})5960// Nested route61const book = app.route('/book')62book.get('/', (c) => c.text('List Books'))63book.get('/:id', (c) => {64 const id = c.req.param('id')65 return c.text('Get Book: ' + id)66})67book.post('/', (c) => c.text('Create Book'))6869// Redirect70app.get('/redirect', (c) => c.redirect('/'))71// Authentication required72app.get('/auth/*', (c) => c.text('You are authorized'))73// ETag74app.get('/etag/cached', (c) => c.text('Is this cached?'))7576// Async77app.get('/fetch-url', async (c) => {78 const response = await fetch('https://example.com/')79 return c.text(`https://example.com/ is ${response.status}`)80})8182// Request headers83app.get('/user-agent', (c) => {84 const userAgent = c.req.header('User-Agent')85 return c.text(`Your UserAgent is ${userAgent}`)86})8788// JSON89app.get('/api/posts', (c) => {90 const posts = [91 { id: 1, title: 'Good Morning' },92 { id: 2, title: 'Good Aternoon' },93 { id: 3, title: 'Good Evening' },94 { id: 4, title: 'Good Night' },95 ]96 return c.json(posts)97})98// status code99app.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))100// default route101app.get('/api/*', (c) => c.text('API endpoint is not found', 404))102103app.post('/form', async (c) => {104 return c.json(c.req.parsedBody || {})105 //return new Response('ok /form')106})107108// Throw Error109app.get('/error', () => {110 throw Error('Error has occurred')111})112app.get('/type-error', () => 'return not Response instance')113114// addEventListener115app.fire()
deleted:examples/basic/package.json-19 removed
deleted:examples/basic/README.md-11 removed
deleted:examples/basic/wrangler.toml-3 removed
deleted:examples/blog/src/controller.ts-53 removed
deleted:examples/blog/src/index.test.ts-79 removed
deleted:examples/blog/src/index.ts-21 removed
deleted:examples/blog/src/model.ts-71 removed
deleted:examples/blog/.gitignore-6 removed
1dist2node_modules3worker4package-lock.json5yarn.lock6wrangler.toml
deleted:examples/blog/jest.config.js-8 removed
1module.exports = {2 testEnvironment: 'miniflare',3 testMatch: ['**/test/**/*.+(ts|tsx|js)', '**/src/**/(*.)+(spec|test).+(ts|tsx|js)'],4 transform: {5 '^.+\\.(ts|tsx)$': 'esbuild-jest',6 },7 resolver: 'jest-node-exports-resolver',8}
deleted:examples/blog/package.json-26 removed
1{2 "name": "hono-example-blog",3 "version": "0.0.1",4 "description": "",5 "main": "dist/index.js",6 "scripts": {7 "build": "esbuild --bundle --outdir=dist ./src/index.ts",8 "dev": "miniflare --live-reload --debug",9 "deploy": "wrangler publish dist/index.js",10 "test": "NODE_OPTIONS=--experimental-vm-modules jest --verbose"11 },12 "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",13 "license": "MIT",14 "dependencies": {15 "hono": "^0.5.4"16 },17 "devDependencies": {18 "@cloudflare/workers-types": "^3.3.1",19 "esbuild": "^0.14.21",20 "esbuild-jest": "^0.5.0",21 "jest": "^27.5.0",22 "jest-environment-miniflare": "^2.2.0",23 "jest-node-exports-resolver": "^1.1.5",24 "miniflare": "^2.3.0"25 }26}
deleted:examples/blog/README.md-75 removed
1# hono-example-blog23CRUD web API for Blog.45## Features67- Cloudflare Workers8- KV9- TypeScript10- `esbuild` for build11- `miniflare` for development12- `wrangler@beta` for deploy13- Test with Jest `miniflare environment`1415## Endpoints1617- `GET /posts`18- `POST /posts`19- `GET /posts/:id`20- `PUT /posts/:id`21- `DELETE /posts/:id`2223## Usage2425Install dependencies:2627```sh28$ yarn run install29```3031Rename `wrangler.example.toml` to `wrangler.toml`:3233```sh34$ mv wrangler.example.toml wrangler.toml35```3637Setup KV:3839```sh40$ wrangler kv:namespace create BLOG_EXAMPLE --preview4142🌀 Creating namespace with title "hono-example-blog-BLOG_EXAMPLE_preview"43✨ Success!44Add the following to your configuration file in your kv_namespaces array:45{ binding = "BLOG_EXAMPLE", preview_id = "xxxxxxxxxx" }46```4748```sh49$ wrangler kv:namespace create BLOG_EXAMPLE5051🌀 Creating namespace with title "hono-example-blog-BLOG_EXAMPLE"52✨ Success!53Add the following to your configuration file in your kv_namespaces array:54{ binding = "BLOG_EXAMPLE", id = "yyyyyyyyyy" }55```5657Copy KV id:5859```toml60kv_namespaces = [61 { binding = "BLOG_EXAMPLE", preview_id = "xxxxxxxxxx", id = "yyyyyyyyy" }62]63```6465Run a development server:6667```sh68$ yarn dev69```7071Publish:7273```sh74$ yarn deploy75```
deleted:examples/blog/wrangler.example.toml-15 removed
1name = "hono-example-blog"2type = "javascript"3workers_dev = true45compatibility_date = "2022-02-03"67kv_namespaces = [8 { binding = "BLOG_EXAMPLE", preview_id = "", id = "" }9]1011[build]12command = "yarn run build"1314[build.upload]15format = "service-worker"
deleted:examples/compute-at-edge/src/index.ts-22 removed
1import { SHA256 } from 'crypto-js'2import { Hono } from 'hono'3import { basicAuth } from 'hono/basic-auth'45const app = new Hono()67app.use(8 '/auth/*',9 basicAuth({10 username: 'compute',11 password: 'edge',12 hashFunction: (m: string) => SHA256(m).toString(),13 })14)1516app.get('/', (c) => c.text('Hello! Compute@Edge!'))17app.get('/auth/*', (c) => c.text('You are authorized!'))18app.get('/hello/:name', (c) => {19 return c.text(`Hello ${c.req.param('name')}!!!!!`)20})2122app.fire()
deleted:examples/compute-at-edge/.gitignore-6 removed
1/node_modules2/bin3/pkg4fastly.toml5package-lock.json6yarn.lock
deleted:examples/compute-at-edge/build.js-21 removed
1const { build } = require('esbuild')2const globalsPlugin = require('@esbuild-plugins/node-globals-polyfill')3const modulesPlugin = require('@esbuild-plugins/node-modules-polyfill')45build({6 entryPoints: ['src/index.ts'],7 bundle: true,8 minify: true,9 outfile: 'bin/index.js',10 platform: 'node',11 plugins: [12 globalsPlugin.NodeGlobalsPolyfillPlugin({13 process: true,14 buffer: true,15 }),16 modulesPlugin.NodeModulesPolyfillPlugin(),17 ],18}).catch((error) => {19 console.error(error)20 process.exit(1)21})
deleted:examples/compute-at-edge/fastly.example.toml-9 removed
1# This file describes a Fastly Compute@Edge package. To learn more visit:2# https://developer.fastly.com/reference/fastly-toml/34authors = ["yusuke@kamawada.com"]5description = "Hono example for Fastly Compute@Edge"6language = "javascript"7manifest_version = 28name = ""9service_id = ""
deleted:examples/compute-at-edge/package.json-24 removed
1{2 "name": "hono-example-compute-at-edge",3 "version": "0.0.1",4 "main": "index.js",5 "author": "yusuke@kamawada.com",6 "license": "MIT",7 "scripts": {8 "dev": "fastly compute serve --watch",9 "prebuild": "node ./build.js",10 "build": "js-compute-runtime --skip-pkg bin/index.js bin/main.wasm",11 "deploy": "npm run build && fastly compute deploy"12 },13 "devDependencies": {14 "@esbuild-plugins/node-globals-polyfill": "^0.1.1",15 "@esbuild-plugins/node-modules-polyfill": "^0.1.4",16 "@types/crypto-js": "^4.1.1",17 "esbuild": "^0.14.25"18 },19 "dependencies": {20 "@fastly/js-compute": "^0.2.4",21 "crypto-js": "^4.1.1",22 "hono": "^0.5.2"23 }24}
deleted:examples/compute-at-edge/README.md-47 removed
1# Hono example for Fastly Compute@Edge23This is an example project with Hono\[炎\] for Fastly Compute@Edge.45## Features67- Minimal8- TypeScript9- [esbuild](https://github.com/evanw/esbuild) to build10- Fast11- Live reload12- Basic Auth middleware1314## Usage1516Install1718```19$ yarn install20```2122Rename and edit `fastly.toml`2324```25$ mv fastly.example.toml fastly.toml26$ code fastly.toml27```2829Develop3031```32$ yarn dev33```3435Deploy3637```38$ yarn deploy39```4041## Author4243Yusuke Wada <https://github.com/yusukebe>4445## License4647MIT
deleted:examples/durable-objects/src/counter.ts-35 removed
1import { Hono } from '../../../src/index'23export class Counter {4 value: number = 05 state: DurableObjectState6 app: Hono = new Hono()78 constructor(state: DurableObjectState) {9 this.state = state10 this.state.blockConcurrencyWhile(async () => {11 const stored = await this.state.storage?.get<number>('value')12 this.value = stored || 013 })1415 this.app.get('/increment', async (c) => {16 const currentValue = ++this.value17 await this.state.storage?.put('value', this.value)18 return c.text(currentValue.toString())19 })2021 this.app.get('/decrement', async (c) => {22 const currentValue = --this.value23 await this.state.storage?.put('value', this.value)24 return c.text(currentValue.toString())25 })2627 this.app.get('/', async (c) => {28 return c.text(this.value.toString())29 })30 }3132 async fetch(request: Request) {33 return this.app.fetch(request)34 }35}
deleted:examples/durable-objects/src/index.ts-26 removed
1import { Hono } from 'hono'23export { Counter } from './counter'45declare module 'hono' {6 interface Env {7 COUNTER: DurableObjectNamespace8 }9}1011const app = new Hono()1213app.get('*', async (c) => {14 const id = c.env.COUNTER.idFromName('A')15 const obj = c.env.COUNTER.get(id)16 const resp = await obj.fetch(c.req.url)1718 if (resp.status === 404) {19 return c.text('404 Not Found', 404)20 }2122 const count = parseInt(await resp.text())23 return c.text(`Count is ${count}`)24})2526export default app
deleted:examples/durable-objects/.gitignore-5 removed
1dist2node_modules3worker4package-lock.json5yarn.lock
deleted:examples/durable-objects/package.json-19 removed
1{2 "private": true,3 "name": "hono-example-durable-objects",4 "version": "0.0.1",5 "main": "dist/index.js",6 "scripts": {7 "test": "echo \"Error: no test specified\" && exit 1",8 "dev": "wrangler dev src/index.ts",9 "deploy": "wrangler publish src/index.ts"10 },11 "license": "MIT",12 "devDependencies": {13 "@cloudflare/workers-types": "^3.0",14 "wrangler": "^0.0.17"15 },16 "dependencies": {17 "hono": "^0.5.1"18 }19}
deleted:examples/durable-objects/README.md-5 removed
1# hono-example-durable-objects23- Cloudflare Durable Objects4- Module Worker Syntax5- Using TypeScript
deleted:examples/durable-objects/wrangler.toml-10 removed
1name = "durable-objects-counter"2type = "javascript"3compatibility_date = "2022-02-12"45[durable_objects]6bindings = [{name = "COUNTER", class_name = "Counter"}]78[[migrations]]9tag = "v1" # Should be unique for each entry10new_classes = ["Counter"]
deleted:examples/jsx-ssr/src/components/footer.tsx-11 removed
1import Nano from 'nano-jsx'23export const Footer = () => {4 return (5 <footer>6 <address>7 Built with <a href='https://github.com/honojs/hono'>Hono</a>8 </address>9 </footer>10 )11}
deleted:examples/jsx-ssr/src/components/header.tsx-11 removed
1import Nano from 'nano-jsx'23export const Header = () => {4 return (5 <header>6 <h1>7 <a href='/'>Hono Example</a>8 </h1>9 </header>10 )11}
deleted:examples/jsx-ssr/src/pages/page.tsx-25 removed
1import Nano from 'nano-jsx'2import { Helmet } from 'nano-jsx'3import { Header } from '../components/header'4import { Footer } from '../components/footer'5import type { Post } from '../index'67type Props = {8 post: Post9}1011export const Page = (props: Props) => {12 return (13 <div>14 <Helmet>15 <title>{props.post.title}</title>16 </Helmet>17 <Header />18 <main>19 <h2>{props.post.title}</h2>20 <p>{props.post.body}</p>21 </main>22 <Footer />23 </div>24 )25}
deleted:examples/jsx-ssr/src/pages/top.tsx-34 removed
1import Nano from 'nano-jsx'2import { Helmet } from 'nano-jsx'3import { Header } from '../components/header'4import { Footer } from '../components/footer'5import type { Post } from '../index'67type Props = {8 posts: Post[]9}1011export const Top = (props: Props) => {12 return (13 <div>14 <Helmet>15 <title>Top</title>16 </Helmet>17 <Header />18 <main>19 <h2>Posts</h2>20 {props.posts}21 <ul>22 {props.posts.map((post) => {23 return (24 <li>25 <a href={`/post/${post.id}`}>{post.title}</a>26 </li>27 )28 })}29 </ul>30 </main>31 <Footer />32 </div>33 )34}
deleted:examples/jsx-ssr/src/index.tsx-46 removed
1import { Hono } from 'hono'2import Nano from 'nano-jsx'3import { Page } from './pages/page'4import { Top } from './pages/top'5import { render } from './renderer'67const app = new Hono()89// Model10export type Post = {11 id: string12 title: string13 body: string14}1516const posts: Post[] = [17 { id: '1', title: 'Good Morning', body: 'Let us eat breakfast' },18 { id: '2', title: 'Good Afternoon', body: 'Let us eat Lunch' },19 { id: '3', title: 'Good Evening', body: 'Let us eat Dinner' },20 { id: '4', title: 'Good Night', body: 'Let us drink Beer' },21 { id: '5', title: 'こんにちは', body: '昼からビールを飲みます' },22]2324// Logic25const getPosts = () => posts2627const getPost = (id: string) => {28 return posts.find((post) => post.id == id)29}3031// Controller32app.get('/', (c) => {33 const posts = getPosts()34 const html = render(<Top posts={posts} />)35 return c.html(html)36})3738app.get('/post/:id{[0-9]+}', (c) => {39 const id = c.req.param('id')40 const post = getPost(id)41 if (!post) return c.notFound()42 const html = render(<Page post={post} />)43 return c.html(html)44})4546app.fire()
deleted:examples/jsx-ssr/src/renderer.tsx-22 removed
1import Nano from 'nano-jsx'2import { Helmet } from 'nano-jsx'34export const render = (component: any) => {5 const app = Nano.renderSSR(component)6 const { body, head, footer, attributes } = Helmet.SSR(app)7 const html = `8<!DOCTYPE html>9<html ${attributes.html.toString()}>10 <head>11 <meta charset="UTF-8">12 <meta name="viewport" content="width=device-width, initial-scale=1.0">13 <link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/mini.css/3.0.1/mini-default.min.css' />14 ${head.join('\n')}15 </head>16 <body ${attributes.body.toString()} style="padding: 1em 2em">17 ${body}18 ${footer.join('\n')}19 </body>20</html>`21 return html22}
deleted:examples/jsx-ssr/.gitignore-5 removed
1dist2node_modules3worker4package-lock.json5yarn.lock
deleted:examples/jsx-ssr/package.json-21 removed
1{2 "name": "hono-example-jsx-ssr",3 "version": "0.0.1",4 "description": "",5 "main": "dist/index.js",6 "scripts": {7 "build": "esbuild --bundle --sourcemap --outdir=dist ./src/index.tsx",8 "dev": "miniflare --live-reload --debug",9 "deploy": "wrangler publish dist/index.js"10 },11 "license": "MIT",12 "dependencies": {13 "hono": "^0.5.1",14 "nano-jsx": "^0.0.29"15 },16 "devDependencies": {17 "esbuild": "^0.14.25",18 "miniflare": "2.2.0",19 "wrangler": "^0.0.16"20 }21}
deleted:examples/jsx-ssr/tsconfig.json-6 removed
1{2 "compilerOptions": {3 "jsx": "react",4 "jsxFactory": "Nano.h",5 }6}
deleted:examples/jsx-ssr/wrangler.toml-10 removed
1name = "hono-example-jsx-ssr"2type = "javascript"34compatibility_date = "2022-01-08"56[build]7command = "yarn run build"89[build.upload]10format = "service-worker"
deleted:examples/mustache/src/index.js-16 removed
1import { Hono } from 'hono'2import { mustache } from 'hono/mustache'34const app = new Hono()56app.use('*', mustache())78app.get('/', (c) => {9 return c.render(10 'index',11 { name: 'Hono[炎]', title: 'Hono mustache example' }, // Parameters12 { footer: 'footer', header: 'header' } // Partials13 )14})1516app.fire()
deleted:examples/mustache/view/footer.mustache-2 removed
1 </body>2</html>
deleted:examples/mustache/view/header.mustache-7 removed
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8" />5 <title>{{title}}</title>6 </head>7 <body>
deleted:examples/mustache/view/index.mustache-3 removed
1{{> header}}2<h1>Hello! {{name}}</h1>3{{> footer}}
deleted:examples/mustache/.gitignore-6 removed
1dist2node_modules3worker4workers-site5package-lock.json6yarn.lock
deleted:examples/mustache/package.json-18 removed
1{2 "name": "hono-example-mustache",3 "version": "0.0.1",4 "main": "src/index.js",5 "scripts": {6 "test": "echo \"Error: no test specified\" && exit 1",7 "dev": "wrangler dev src/index.js",8 "deploy": "wrangler publish src/index.js"9 },10 "license": "MIT",11 "dependencies": {12 "hono": "^0.5.1",13 "mustache": "^4.2.0"14 },15 "devDependencies": {16 "wrangler": "^0.0.16"17 }18}
deleted:examples/mustache/wrangler.toml-5 removed
1name = "hono-example-mustache"2compatibility_date = "2022-02-12"34[site]5bucket = "./view"
deleted:examples/serve-static/assets/static/demo/index.html-6 removed
1<html>2 <body>3 <h1>Hello Hono!</h1>4 <img src="/static/images/dinotocat.png" alt="Dinotocat" />5 </body>6</html>
deleted:examples/serve-static/assets/static/images/dinotocat.pngbinary

A binary file, deleted.

deleted:examples/serve-static/assets/static/hello.txt-1 removed
1This is hello.txt! You can access: /static/demo/
deleted:examples/serve-static/src/index.js-9 removed
1import { Hono } from 'hono'2import { serveStatic } from 'hono/serve-static'34const hono = new Hono()56hono.use('/static/*', serveStatic({ root: './' }))7hono.get('/', (c) => c.text('This is Home! You can access: /static/hello.txt'))89hono.fire()
deleted:examples/serve-static/.gitignore-5 removed
1dist2node_modules3worker4package-lock.json5yarn.lock
deleted:examples/serve-static/package.json-18 removed
1{2 "name": "hono-example-serve-static",3 "version": "0.0.1",4 "description": "",5 "main": "src/index.js",6 "scripts": {7 "test": "echo \"Error: no test specified\" && exit 1",8 "dev": "wrangler dev src/index.js",9 "deploy": "wrangler publish src/index.js"10 },11 "license": "MIT",12 "dependencies": {13 "hono": "^0.5.1"14 },15 "devDependencies": {16 "wrangler": "^0.0.16"17 }18}
deleted:examples/serve-static/wrangler.toml-5 removed
1name = "hono-example-serve-static"2compatibility_date = "2022-02-12"34[site]5bucket = "./assets"
modified:src/middleware/mustache/README.md+1 added-1 removed
66 unmodified lines
67```6869## Example7071<https://github.com/honojs/hono/tree/master/examples/mustache>71<https://github.com/honojs/examples/tree/master/mustache-template>
modified:src/middleware/serve-static/README.md+1 added-1 removed
37 unmodified lines
38```3940## Example4142<https://github.com/honojs/hono/tree/master/examples/serve-static>42<https://github.com/honojs/examples/tree/master/serve-static>