-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
79 lines (66 loc) · 2.23 KB
/
server.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
const path = require('path')
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const { graphqlExpress } = require('apollo-server-express')
const expressPlayground = require('graphql-playground-middleware-express')
.default
const { AUTO } = require('jimp')
const transformImage = require('./src/transform-image')
const getFiles = require('./src/getFiles')
const getOneCat = require('./src/getOneCat')
const getRandom = require('./src/getRandom')
const schema = require('./src/graphQL-utils')
const index = path.join(__dirname, 'src/index.html')
const app = express()
app.use(express.static(path.join(__dirname, 'src')))
app.use(express.static(path.resolve(__dirname, 'images')))
app.use(cors())
app.use(
'/graphql',
bodyParser.json(),
graphqlExpress(req => ({
schema,
context: { req }
}))
)
// GraphiQL, a visual editor for queries
app.use('/graphiql', expressPlayground({ endpoint: '/graphql' }))
app
.get('/cat', async (req, res) =>
res.json({
cat: await getOneCat(req)
})
)
.get('/placeholder', async (req, res) => {
const cat = await getOneCat(req, true)
res.sendFile(cat, { root: '/' })
})
.get('/placeholder/:width', async (req, res) => {
const width = parseInt(req.params.width, 10)
const cat = await getOneCat(req, true)
return transformImage(cat, width, AUTO, res)
})
.get('/placeholder/:width/:height', async (req, res) => {
const width = parseInt(req.params.width, 10)
const height = parseInt(req.params.height, 10)
const cat = await getOneCat(req, true)
return transformImage(cat, width, height, res)
})
.get('/cats/:length', async (req, res) => {
const files = await getFiles(req)
const length =
req.params.length > files.length ? files.length : req.params.length
const cats = getRandom(files, length)
if (length < 1 || !Number.isInteger(parseInt(length))) {
res.status(500).send({ error: 'You need to ask for at least one cat' })
}
res.json({
cats
})
})
.get('/', (_, res) => res.sendFile(index))
.get('/images/:file', (req, res) => {
res.sendFile(path.join(__dirname, req.path))
})
app.listen(3000, () => console.log('Cat API is on http://localhost:3000/'))