forked from startupstockphotos/api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (77 loc) · 2.11 KB
/
index.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
83
84
85
86
87
88
89
90
91
const url = require('url')
const qs = require('qs')
const Fuse = require('fuse.js')
const api = require('router')()
const database = require('./database.js')
const { NOW } = process.env
const origin = NOW ? 'https://api.startupphotos.com' : 'http://localhost:3001'
const db = database.map(({ id, tags, description }) => ({
id,
tags,
description,
images: {
placeholder: `${origin}/static/processed/${id}/placeholder.jpg`,
display: `${origin}/static/processed/${id}/display.jpg`,
raw: `${origin}/static/raw/${id}.jpg`
}
}))
const index = new Fuse(db, {
keys: [
'tags',
'description'
]
})
api.get('/photos', (req, res) => {
const args = qs.parse(url.parse(req.url) || '')
const limit = args.limit ? parseInt(args.limit) : 18
const page = args.page ? parseInt(args.page) : null
const offset = args.offset ? parseInt(args.offset) : null
let results
if (page !== null || offset !== null) {
const start = offset || (limit * page || 0)
const end = ((page || 0) + 1) * limit
results = db.slice(start, end)
} else {
results = db.slice(0, limit)
}
res.end(JSON.stringify(results))
})
api.get('/photos/:id', (req, res) => {
const { id } = req.params
const photo = db.filter(i => i.id === id)[0]
if (photo) {
res.end(JSON.stringify(photo))
} else {
res.statusCode = 404
res.end(JSON.stringify({
errors: [
`photo ${id} does not exist`
]
}))
}
})
api.get('/search/:query', (req, res) => {
const { query } = req.params
res.end(JSON.stringify(index.search(query)))
})
require('connect')()
.use(require('compression')())
.use('/static/raw', require('serve-static')('raw', {
setHeaders (res, path) {
res.setHeader('Content-Disposition', require('content-disposition')(path))
}
}))
.use('/static/processed', require('serve-static')('static', {
maxAge: '1d'
}))
.use((req, res, next) => {
res.setHeader('Content-Type', 'application/json')
next()
})
.use('/api/v1', api)
.use((req, res) => {
res.end(JSON.stringify({
message: 'Welcome to the Startup Stock Photos API'
}))
})
.listen(3001)