feat: Use KV for blog example (#60)
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 fbde907 · Browse files · 8 files·+72 added−42 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+72 added−42 removed
- tests:+1 added−0 removed
- other:+71 added−42 removed
Provenance
- Commit
034bf6d- Tree
9c355dc- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
fbde907
8 files changed+72 added−42 removed
modified:example/blog/src/controller.test.ts+1 added
33 unmodified lines34353637383940414235 unmodified lines33 unmodified lines 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']).not.toBeUndefined() expect(body['posts'].length).toBe(1)
req = new Request(`https://localhost/posts/${newPost.id}`) res = await app.dispatch(req)35 unmodified linesmodified:example/blog/src/controller.ts+13 added-10 removed
3 unmodified lines4567898910111213141514151617181920212223242526272528293031323334353634373839403839414243444546474548495051495253543 unmodified linesexport const root: Handler = (c) => { return c.json({ message: 'Hello' })}
export const list: Handler = (c) => { const posts = Model.getPosts()export const list: Handler = async (c) => { const posts = await Model.getPosts() return c.json({ posts: posts, ok: true })}
export const create: Handler = async (c) => { let newPost: Model.Post | undefined if (c.req.parsedBody) { const param = (await c.req.json()) as Model.Param const newPost = Model.createPost(param) const param = c.req.parsedBody as Model.Param newPost = await 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) const post = await 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)) { if (!(await 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) const param = c.req.parsedBody as Model.Param const success = await 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)) { if (!(await Model.getPost(id))) { // 204 No Content return c.json({ ok: false }, 204) } const success = Model.deletePost(id) const success = await Model.deletePost(id) return c.json({ ok: success })}modified:example/blog/src/index.ts+2 added
123456789107 unmodified linesimport { Hono, Middleware } from '../../../dist'import * as Controller from './controller'
export const app = new Hono()
app.use('/posts/*', Middleware.bodyParse())app.use('/posts/*', Middleware.cors())
app.get('/', Controller.root)
7 unmodified linesmodified:example/blog/src/model.ts+39 added-21 removed
1+declare const BLOG_EXAMPLE: KVNamespace2+const PREFIX = 'v1:post:'3+4 declare global {5 interface Crypto {6 randomUUID(): string7 }9 unmodified lines17 title: string18 body: string19 }20 18-const posts: { [key: string]: Post } = {}21+const generateID = (key: string) => {22+ return `${PREFIX}${key}`23+}24 20-export const getPosts = (): Post[] => {21- return Object.values(posts)25+export const getPosts = async (): Promise<Post[]> => {26+ const list = await BLOG_EXAMPLE.list({ prefix: PREFIX })27+ const keys = list.keys28+29+ const posts: Post[] = []30+31+ for (const key of keys) {32+ const value = await BLOG_EXAMPLE.get(key.name)33+ if (!value) continue34+ const post: Post = JSON.parse(value)35+ posts.push(post)36+ }37+38+ return posts39 }40 24-export const getPost = (id: string): Post | undefined => {25- return posts[id]41+export const getPost = async (id: string): Promise<Post | undefined> => {42+ const value = await BLOG_EXAMPLE.get(generateID(id))43+ if (!value) return44+ const post: Post = JSON.parse(value)45+ return post46 }47 28-export const createPost = (param: Param): Post | undefined => {48+export const createPost = async (param: Param): Promise<Post | undefined> => {49 if (!(param.title && param.body)) return50 const id = crypto.randomUUID()51 const newPost: Post = { id: id, title: param.title, body: param.body }32- posts[id] = newPost52+ await BLOG_EXAMPLE.put(generateID(id), JSON.stringify(newPost))53 return newPost54 }55 36-export const updatePost = (id: string, param: Param): boolean => {56+export const updatePost = async (id: string, param: Param): Promise<boolean> => {57 if (!(param.title && param.body)) return false38- const post = posts[id]39- if (post) {40- post.title = param.title41- post.body = param.body42- return true43- }44- return false58+ const post = await getPost(id)59+ if (!post) return false60+ post.title = param.title61+ post.body = param.body62+ await BLOG_EXAMPLE.put(generateID(id), JSON.stringify(post))63+ return true64 }65 47-export const deletePost = (id: string): boolean => {48- if (posts[id]) {49- delete posts[id]50- return true51- }52- return false66+export const deletePost = async (id: string): Promise<boolean> => {67+ const post = await getPost(id)68+ if (!post) return false69+ await BLOG_EXAMPLE.delete(generateID(id))70+ return true71 }modified:example/blog/.gitignore+2 added-1 removed
1 dist2 node_modules3 worker4 package-lock.json5-yarn.lock5+yarn.lock6+wrangler.tomlmodified:example/blog/README.md+2 added-1 removed
12344567895 unmodified lines# hono-example-blog
- CRUD- KV- Using TypeScript- TypeScript- Test with Jest `miniflare environment`
## Endpoints
5 unmodified linesadded:example/blog/wrangler.example.toml+13 added
12345678910111213name = "hono-example-blog"type = "webpack"route = ''zone_id = ''usage_model = ''compatibility_flags = []workers_dev = truecompatibility_date = "2022-01-09"webpack_config = "webpack.config.js"
kv_namespaces = [ { binding = "BLOG_EXAMPLE", preview_id = "", id = "" }]deleted:example/blog/wrangler.toml-9 removed
123456789name = "hono-example-blog"type = "webpack"route = ''zone_id = ''usage_model = ''compatibility_flags = []workers_dev = truecompatibility_date = "2022-01-09"webpack_config = "webpack.config.js"No newline at end of file