-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (62 loc) · 1.82 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
/*
* API Creation
*
* Use a JSON file as a database
* add Employee -> adds an element to the database
* del Employee -> deletes an element to the database
* search Employee -> searches through the array and prints the result
*
*/
// Library variables
var express = require("express");
var fs = require("fs");
var router = express.Router();
var jwt = require('jsonwebtoken');
var body = require('body-parser');
var addItems = require('./operations/addItems');
var modFile = require('./operations/modFile');
var deleteItem = require('./operations/deleteItem');
// Reading the file using File System and returns the buffer
var file = fs.readFileSync("data.json");
// Parses the file and converts into JSON objects in
// workers variable
var workers = JSON.parse(file);
module.exports.workers = workers;
var app = express();
app.use(body.urlencoded({extended:true}));
app.use(body.json());
app.use("/api", router);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, token, Content-Type, Accept");
next();
});
router.use(function(req, resp, next){
var token = req.headers["token"];
if(token){
jwt.verify(token, process.env.SECRET_KEY, function(err, decode){
if(err){
resp.status(401).send({
msg: "Token Expired or Invalid Token"
});
} else{
next();
}
});
} else if(req.method === "OPTIONS"){
resp.status(200).send("Connected");
}
else{
resp.status(400).send("Bad Request");
console.log(req.method);
}
});
// Add Employee
router.post("/emp", addItems.add);
// Modify the existing data
router.put("/emp", modFile.mod);
// Delete an employee
router.delete("/emp", deleteItem.del);
// API Calls
require('./auth/apiService')(app, workers);