forked from khabdrick/api-key-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.js
56 lines (44 loc) · 1.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
const express = require('express');
const app = express();
const port = 4000;
const API = require('./apiAuth');
// Get initial data for users and countries
const { users, Countries } = require('./initialData');
//handle json body request
app.use(express.json());
app.get('/', (req, res) => {
//home page
res.status(200).send({ data: { message: 'You can get list of countires at /api/country.' } });
});
app.post('/api/register', (req, res) => {
//create a new with "user:Username"
let username = req.body.username;
let user = API.createUser(username, req);
res.status(201).send({ data: user });
});
app.get('/api/country', API.authenticateKey, (req, res) => {
//get list of all Countries
let today = new Date().toISOString().split('T')[0];
console.log(today);
res.status(200).send({
data: Countries,
});
});
app.post('/api/country', API.authenticateKey, (req, res) => {
//add a new country /:apikey
let country = {
_id: Date.now(),
name: req.body.country,
};
Countries.push(country);
res.status(201).send({
data: country,
});
});
app.listen(port, function (err) {
if (err) {
console.error('Failure to launch server');
return;
}
console.log(`Listening on port ${port}`);
});