-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
72 lines (55 loc) · 1.87 KB
/
app.ts
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
import express from "express";
const logger = require('morgan');
const products = require('./routes/products') ;
const users = require('./routes/users');
const mongoose = require('./config/database'); //database configuration
const jwt = require('jsonwebtoken');
const app = express();
const serverless = require('serverless-http')
app.set('secretKey', 'nodeRestApi'); // jwt secret token
// connection to mongodb
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(logger('dev'));
app.use(express.urlencoded({extended: false}));
app.get('/', function(req, res){
res.json({"Welcome to the Product Inventory" : "Register/Login to Access!"});
});
// public route
app.use('/users', users);
// private route
app.use('/products', validateUser, products);
// avoiding 404 on icon showing by caching No Content status
app.get('/favicon.ico', function(req, res) {
res.sendStatus(204);
});
function validateUser(req, res, next) {
jwt.verify(req.headers['x-access-token'], req.app.get('secretKey'), function(err, decoded) {
if (err) {
res.json({status:"error", message: err.message, data:null});
}else{
// add user id to request
req.body.userId = decoded.id;
next();
}
});
}
// express doesn't consider not found 404 as an error so we need to handle 404 it explicitly
// handle 404 error
app.use(function(req, res, next) {
let err = new Error('Not Found');
res.status(404);
next(err);
});
// handle errors
app.use(function(err, req, res, next) {
console.log(err);
if(err.status === 404)
res.status(404).json({message: "Not found"});
else
res.status(500).json({message: "Something looks wrong :( !!!"});
});
app.listen(3000, function(){
console.log('Node server listening on port 3000');
});
// wrap express app instance with serverless http function
module.exports.handler = serverless(app)