/
pictures.js
82 lines (69 loc) · 1.96 KB
/
pictures.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
76
77
78
79
80
81
82
'use strict'
import { send, json } from 'micro'
import HttpHash from 'http-hash'
import Db from 'platzigram-db'
import config from './config'
import DbStub from './test/stub/db'
import utils from './lib/utils'
const env = process.env.NODE_ENV || 'production'
let db = new Db(config.db)
if (env === 'test') {
db = new DbStub()
}
const hash = HttpHash()
hash.set('GET /tag/:tag', async function byTag (req, res, params) {
let tag = params.tag
await db.connect()
let images = await db.getImagesByTag(tag)
await db.disconnect()
send(res, 200, images)
})
hash.set('GET /list', async function list (req, res, params) {
await db.connect()
let images = await db.getImages()
await db.disconnect()
send(res, 200, images)
})
hash.set('GET /:id', async function getPicture (req, res, params) {
let id = params.id
await db.connect()
let image = await db.getImage(id)
await db.disconnect()
send(res, 200, image)
})
hash.set('POST /', async function postPicture (req, res, params) {
let image = await json(req)
try {
let token = await utils.extractToken(req)
let encoded = await utils.verifyToken(token, config.secret, {})
if (encoded && encoded.userId !== image.userId) {
throw new Error('invalid token')
}
} catch (e) {
return send(res, 401, { error: 'invalid token' })
}
await db.connect()
let created = await db.saveImage(image)
await db.disconnect()
send(res, 201, created)
})
hash.set('POST /:id/like', async function likePicture (req, res, params) {
let id = params.id
await db.connect()
let image = await db.likeImage(id)
await db.disconnect()
send(res, 200, image)
})
export default async function main (req, res) {
let { method, url } = req
let match = hash.get(`${method.toUpperCase()} ${url}`)
if (match.handler) {
try {
await match.handler(req, res, match.params)
} catch (e) {
send(res, 500, { error: e.message })
}
} else {
send(res, 404, { error: 'route not found' })
}
}