-
Notifications
You must be signed in to change notification settings - Fork 8
/
server.js
90 lines (73 loc) · 2.19 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
80
81
82
83
84
85
86
87
88
89
90
const express = require('express');
const next = require('next');
const path = require('path');
const dynamoose = require('dynamoose');
if (process.env.NODE_ENV === 'development') {
require('dotenv').config({ path: path.resolve(__dirname, `./env/${process.env.ENV_FILE}`) });
}
// Configure Dynamoose
// The accessKeyId & secretAccessKey can be made avaialble via the IAMRole
dynamoose.AWS.config.update({
region: process.env.SERVICE_AWS_REGION,
});
if (process.env.NODE_ENV === 'development') {
/*
For development environment, atleast with dynamoose library,
you need to pass mock access key & secret.
*/
dynamoose.AWS.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_ACCESS_SECRET,
region: process.env.SERVICE_AWS_REGION,
});
dynamoose.local('http://localhost:8000');
}
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const Dog = require('./models/Dog');
function createServer() {
const server = express();
server.get('/api/dog/:breed', async (req, res) => {
const { breed } = req.params;
try {
const dogData = await Dog.query('breed').eq(breed).exec();
res.send({ s: 'success', d: dogData });
} catch (e) {
res.status(500).send({ s: 'error', m: e.message });
}
});
server.get('/api/mock-dog-create/', async (req, res) => {
try {
const dogs = [{
name: 'Ollie',
breed: 'terrier',
}, {
name: 'Maxi',
breed: 'labrador',
}, {
name: 'Rio',
breed: 'border_collie',
}];
await Dog.batchPut(dogs);
res.send({ s: 'success', m: 'Dogs created successfully', d: dogs });
} catch (e) {
res.status(500).send({ s: 'error', m: e.message });
}
});
server.get('*', (req, res) => (handle(req, res)));
return server;
}
if (dev) {
app.prepare().then(() => {
const server = createServer();
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
} else {
const server = createServer();
module.exports = server;
}