Feature/example blog (#39)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add blog CRUD example * Fixed some * Exclude example test
authored by Yusuke Wada · committed by GitHub · parent 4a795da · Browse files · 12 files·+287 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+287 added−4 removed
- tests:+76 added−0 removed
- other:+211 added−4 removed
Provenance
- Commit
511c0eb- Tree
c92b97f- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
4a795da
12 files changed+287 added−4 removed
added:example/blog/src/controller.test.ts+76 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import { app } from './index'import type { Post } from './model'
describe('Root', () => { it('GET /', async () => { const req = new Request('http://localhost/') const res = await app.dispatch(req) expect(res.status).toBe(200) const body = (await res.json()) as any expect(body['message']).toBe('Hello') })})
describe('Blog API', () => { it('List', async () => { const req = new Request('http://localhost/posts') const res = await app.dispatch(req) expect(res.status).toBe(200) const body = (await res.json()) as any expect(body['posts']).not.toBeUndefined() expect(body['posts'].length).toBe(0) })
it('CRUD', async () => { let payload = JSON.stringify({ title: 'Morning', body: 'Good Morning' }) let req = new Request('http://localhost/posts', { method: 'POST', body: payload }) let res = await app.dispatch(req) expect(res.status).toBe(201) let body = (await res.json()) as any const newPost = body['post'] as Post expect(newPost.title).toBe('Morning') expect(newPost.body).toBe('Good Morning')
req = new Request('https://localhost/posts') res = await app.dispatch(req) expect(res.status).toBe(200) body = (await res.json()) as any expect(body['posts'].length).toBe(1)
req = new Request(`https://localhost/posts/${newPost.id}`) res = await app.dispatch(req) expect(res.status).toBe(200) body = (await res.json()) as any let post = body['post'] as Post expect(post.id).toBe(newPost.id) expect(post.title).toBe('Morning')
payload = JSON.stringify({ title: 'Night', body: 'Good Night' }) req = new Request(`https://localhost/posts/${post.id}`, { method: 'PUT', body: payload, }) res = await app.dispatch(req) expect(res.status).toBe(200) body = (await res.json()) as any expect(body['ok']).toBeTruthy()
req = new Request(`https://localhost/posts/${post.id}`) res = await app.dispatch(req) expect(res.status).toBe(200) body = (await res.json()) as any post = body['post'] as Post expect(post.title).toBe('Night') expect(post.body).toBe('Good Night')
req = new Request(`https://localhost/posts/${post.id}`, { method: 'DELETE' }) res = await app.dispatch(req) expect(res.status).toBe(200) body = (await res.json()) as any expect(body['ok']).toBeTruthy()
req = new Request(`https://localhost/posts/${post.id}`) res = await app.dispatch(req) expect(res.status).toBe(404) })})added:example/blog/src/controller.ts+51 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import type { Handler } from '../../../dist'import * as Model from './model'
export const root: Handler = (c) => { return c.json({ message: 'Hello' })}
export const list: Handler = (c) => { const posts = Model.getPosts() return c.json({ posts: posts, ok: true })}
export const create: Handler = async (c) => { const param = (await c.req.json()) as Model.Param const newPost = Model.createPost(param) if (!newPost) { // Is 200 suitable? return c.json({ error: 'Can not create new post', ok: false }, 200) } return c.json({ post: newPost, ok: true }, 201)}
export const show: Handler = async (c) => { const id = c.req.params('id') const post = Model.getPost(id) if (!post) { return c.json({ error: 'Not Found', ok: false }, 404) } return c.json({ post: post, ok: true })}
export const update: Handler = async (c) => { const id = c.req.params('id') if (!Model.getPost(id)) { // 204 No Content return c.json({ ok: false }, 204) } const param = (await c.req.json()) as Model.Param const success = Model.updatePost(id, param) return c.json({ ok: success })}
export const destroy: Handler = async (c) => { const id = c.req.params('id') if (!Model.getPost(id)) { // 204 No Content return c.json({ ok: false }, 204) } const success = Model.deletePost(id) return c.json({ ok: success })}added:example/blog/src/index.ts+14 added
1234567891011121314import { Hono } from '../../../dist'import * as Controller from './controller'
export const app = new Hono()
app.get('/', Controller.root)
app.get('/posts', Controller.list)app.post('/posts', Controller.create)app.get('/posts/:id', Controller.show)app.put('/posts/:id', Controller.update)app.delete('/posts/:id', Controller.destroy)
app.fire()added:example/blog/src/model.ts+53 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253declare global { interface Crypto { randomUUID(): string }}
export interface Post { id: string title: string body: string}
export type Param = { title: string body: string}
const posts: { [key: string]: Post } = {}
export const getPosts = (): Post[] => { return Object.values(posts)}
export const getPost = (id: string): Post | undefined => { return posts[id]}
export const createPost = (param: Param): Post | undefined => { if (!(param.title && param.body)) return const id = crypto.randomUUID() const newPost: Post = { id: id, title: param.title, body: param.body } posts[id] = newPost return newPost}
export const updatePost = (id: string, param: Param): boolean => { if (!(param.title && param.body)) return false const post = posts[id] if (post) { post.title = param.title post.body = param.body return true } return false}
export const deletePost = (id: string): boolean => { if (posts[id]) { delete posts[id] return true } return false}added:example/blog/.gitignore+5 added
1+dist2+node_modules3+worker4+package-lock.json5+yarn.lockadded:example/blog/jest.config.js+7 added
1234567module.exports = { testEnvironment: 'miniflare', // ✨ testMatch: ['**/test/**/*.+(ts|tsx|js)', '**/src/**/(*.)+(spec|test).+(ts|tsx|js)'], transform: { '^.+\\.(ts|tsx)$': 'ts-jest', },}added:example/blog/package.json+30 added
123456789101112131415161718192021222324252627282930{ "name": "hono-example-blog", "version": "0.0.1", "description": "", "main": "dist/worker.js", "scripts": { "test": "jest --verbose", "build": "rimraf tsc && wrangler build", "dev": "tsc && npm-run-all --parallel dev:*", "dev:tsc": "tsc --watch", "dev:wrangler": "wrangler dev" }, "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)", "license": "MIT", "dependencies": { "hono": "^0.0.12" }, "devDependencies": { "@cloudflare/workers-types": "^3.3.0", "@cloudflare/wrangler": "^1.19.7", "@types/jest": "^27.4.0", "jest": "^27.4.7", "jest-environment-miniflare": "^2.0.0", "npm-run-all": "^4.1.5", "ts-jest": "^27.1.2", "typescript": "^4.5.4", "webpack": "^5.65.0", "webpack-cli": "^4.9.1" }}No newline at end of fileadded:example/blog/README.md+13 added
12345678910111213# hono-example-blog
- CRUD- Using TypeScript- Test with Jest `miniflare environment`
## Endpoints
- `GET /posts`- `POST /posts`- `GET /posts/:id`- `PUT /posts/:id`- `DELETE /posts/:id`added:example/blog/tsconfig.json+23 added
1+{2+ "compilerOptions": {3+ "target": "es2017",4+ "module": "commonjs",5+ "rootDir": "src",6+ "outDir": "./dist",7+ "allowJs": true,8+ "strict": true,9+ "esModuleInterop": true,10+ "skipLibCheck": true,11+ "types": [12+ "@cloudflare/workers-types",13+ "@types/jest",14+ "@types/service-worker-mock"15+ ]16+ },17+ "include": [18+ "src/**/*"19+ ],20+ "exclude": [21+ "node_modules",22+ ]23+}added:example/blog/webpack.config.js+4 added
1+module.exports = {2+ target: 'webworker',3+ entry: './dist/index.js',4+}added:example/blog/wrangler.toml+9 added
1+name = "hono-example-blog"2+type = "webpack"3+route = ''4+zone_id = ''5+usage_model = ''6+compatibility_flags = []7+workers_dev = true8+compatibility_date = "2022-01-09"9+webpack_config = "webpack.config.js"modified:jest.config.js+2 added-4 removed
1 module.exports = {2- testMatch: [3- '**/test/**/*.+(ts|tsx|js)',4- '**/src/**/(*.)+(spec|test).+(ts|tsx|js)',5- ],2+ testMatch: ['**/test/**/*.+(ts|tsx|js)', '**/src/**/(*.)+(spec|test).+(ts|tsx|js)'],3 transform: {4 '^.+\\.(ts|tsx)$': 'ts-jest',5 },6+ testPathIgnorePatterns: ['./example'],7 }