-
-
Notifications
You must be signed in to change notification settings - Fork 928
/
server.ts
44 lines (35 loc) · 1.06 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Note: if you're developing a local server and don't expect to get concurrent requests,
// it can be easier to use `JSONFileSync` adapter.
// But if you need to avoid blocking requests, you can do so by using `JSONFile` adapter.
import express from 'express'
import asyncHandler from 'express-async-handler'
import { JSONFilePreset } from '../presets/node.js'
const app = express()
app.use(express.json())
type Post = {
id: string
body: string
}
type Data = {
posts: Post[]
}
const defaultData: Data = { posts: [] }
const db = await JSONFilePreset<Data>('db.json', defaultData)
// db.data can be destructured to avoid typing `db.data` everywhere
const { posts } = db.data
app.get('/posts/:id', (req, res) => {
const post = posts.find((p) => p.id === req.params.id)
res.send(post)
})
app.post(
'/posts',
asyncHandler(async (req, res) => {
const post = req.body as Post
post.id = String(posts.length + 1)
await db.update(({ posts }) => posts.push(post))
res.send(post)
}),
)
app.listen(3000, () => {
console.log('listening on port 3000')
})