-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.js
75 lines (68 loc) · 1.95 KB
/
tasks.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const { Router } = require('express')
const { Firestore } = require('@google-cloud/firestore')
const router = Router()
const db = new Firestore()
router.get('/', async (req, res, next) => {
try {
const tasksSnapshot = await db.collection('tasks').get()
const tasks = []
tasksSnapshot.forEach((task) => {
tasks.push({ id: task.id, ...task.data() })
})
res.json(tasks)
} catch (e) {
next(e)
}
})
router.get('/:id', async (req, res, next) => {
try {
const id = req.params.id
if (!id) throw new Error('Id is blank')
const task = await db.collection('tasks').doc(id).get()
if (!task.exists) throw new Error('Task does not exists')
res.json({ id: task.id, ...task.data() })
} catch (e) {
next(e)
}
})
router.post('/', async (req, res, next) => {
try {
const title = req.body.title
if (!title) throw new Error('Title is blank')
const description = req.body.description || ''
const color = req.body.color || 'white'
const createdAt = Date.now()
const updatedAt = null
const data = { title, description, color, createdAt, updatedAt }
const ref = await db.collection('tasks').add(data)
res.json({ id: ref.id, ...data })
} catch (e) {
next(e)
}
})
router.put('/:id', async (req, res, next) => {
try {
const id = req.params.id
if (!id) throw new Error('Id is blank')
const title = req.body.title
const description = req.body.description || ''
const color = req.body.color || 'white'
const updatedAt = Date.now()
const data = { title, description, color, updatedAt }
await db.collection('tasks').doc(id).set(data, { merge: true })
res.json({ id, ...data })
} catch (e) {
next(e)
}
})
router.delete('/:id', async (req, res, next) => {
try {
const id = req.params.id
if (!id) throw new Error('Id is blank')
await db.collection('tasks').doc(id).delete()
res.json({ id })
} catch (e) {
next(e)
}
})
module.exports = router