Closed6

Hono with Cloudflare Workers

shinkatz104shinkatz104
npm create hono@latest
Need to install the following packages:
create-hono@0.9.2
Ok to proceed? (y) y
create-hono version 0.9.2
? Target directory hono-tutorial
? Which template do you want to use? cloudflare-workers
✔ Cloning the template
? Do you want to install project dependencies? yes
? Which package manager do you want to use? npm
✔ Installing project dependencies
🎉 Copied project files
Get started with: cd hono-tutorial
shinkatz104shinkatz104
npm i

up to date, audited 83 packages in 828ms

12 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
shinkatz104shinkatz104
npm run dev

> dev
> wrangler dev src/index.ts


 ⛅️ wrangler 3.62.0
-------------------


√ Would you like to help improve Wrangler by sending usage metrics to Cloudflare? ... no

Your choice has been saved in the following file: ..\..\AppData\Roaming\xdg.config\.wrangler\metrics.json.

  You can override the user level setting for a project in `wrangler.toml`:

   - to disable sending metrics for a project: `send_metrics = false`
   - to enable sending metrics for a project: `send_metrics = true`
⎔ Starting local server...
[wrangler:inf] Ready on http://127.0.0.1:8787
╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ [b] open a browser, [d] open Devtools, [l] turn off local mode, [c] clear console, [x] to exit                      │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
shinkatz104shinkatz104
src\index.ts
import { Hono } from 'hono'
import { prettyJSON } from 'hono/pretty-json'
import { basicAuth } from 'hono/basic-auth'
import auth from './auth'
import posts from './posts'

const app = new Hono()

app.use("*", prettyJSON())
app.use(
  '/auth/*',
  basicAuth({
    username: "shinkatz104",
    password: "shinkatz104",
  })
)

app.route('/auth', auth)
app.route('/posts', posts)

app.get('/', (c) => {
  return c.text('Hello Hono!')
})

export default app
src\auth.ts
import { Hono } from 'hono'

const app = new Hono()

app.get('/page', (c) => {
  return c.text('You are authorized')
})

export default app
src\posts.ts
import { Hono } from 'hono'
import { prettyJSON } from 'hono/pretty-json'

const app = new Hono()

let posts = [
  {
    id: "1",
    title: "Post 1 Title",
    content: "Post 1 Content"
  },
  {
    id: "2",
    title: "Post 2 Title",
    content: "Post 2 Content"
  },
  {
    id: "3",
    title: "Post 3 Title",
    content: "Post 3 Content"
  },
]

app.use("*", prettyJSON())

// Select Many
app.get('/', (c) => c.json({ posts: posts }))

// Select Find Unique
app.get('/:id', (c) => {
  const id = c.req.param('id')
  const post = posts.find((p) => p.id === id)
  if (post) {
    return c.json(post)
  } else {
    return c.json({ message: 'not found this post' }, 404)
  }
})

// Create
app.post('/', async (c) => {
  const { title, content } = await c.req.json<{ title: string, content: string }>()
  const newPost = { id: String(posts.length + 1), title, content }
  posts = [...posts, newPost]
  return c.json(newPost, 201)
})

// Update
app.put('/:id', async (c) => {
  const id = c.req.param('id')
  const index = posts.findIndex((p) => p.id === id)
  if (index === -1) {
    return c.json({ message: 'not found this post' }, 404)
  }

  const { title, content } = await c.req.json()
  posts[index] = { ...posts[index], title, content }

  return c.json(posts[index])
})

// Delete
app.delete('/:id', async (c) => {
  const id = c.req.param('id')
  const index = posts.findIndex((p) => p.id === id)
  if (index === -1) {
    return c.json({ message: 'not found this post' }, 404)
  }

  posts = posts.filter((p) => p.id !== id)

  return c.json({ message: 'post deleted' })
})

export default app

このスクラップは5ヶ月前にクローズされました