-
Notifications
You must be signed in to change notification settings - Fork 0
/
customerRouter.js
69 lines (58 loc) · 2.15 KB
/
customerRouter.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
const mongoose = require('mongoose');
const express = require('express');
const {check, validationResult} = require('express-validator');
const jwt = require('jsonwebtoken');
const Router = express.Router();
const {secret} = require('./const');
const Customer = require('./Customer');
const conDb = require('./conMainBase');
Router.post(
'/customer',
async (req, res) => {
await conDb();
const {token} = req.body;
let userId = null;
try {
const decoded = jwt.verify(token, secret);
userId = decoded.username.id;
} catch(e) {
return res.status(400).json({message: e.message})
}
let obj = req.body;
const {type, name, cnpj, formalName, email, fone, address, contactPerson} = obj;
// CUSTOMERS
if (obj.type === 'insertCustomer') {
const newCustomer = new Customer({userId, type, name, cnpj, formalName, email, fone, address, contactPerson});
try {
const value = await newCustomer.save();
return res.send({inserted: true, id: value._id});
} catch(e) {
return res.status(400).json({message: e.message});
}
}
if (obj.type === 'getCustomers') {
try {
const customers = await Customer.find({userId});
return res.send(customers);
} catch(e) {
return res.status(400).json({message: e.message});
}
}
if (obj.type === 'updateCustomer') {
try {
const newCustomer = await Customer.updateOne({userId, _id: obj.id}, {...obj});
return res.send({updated: true, id: obj.id});
} catch(e) {
return res.status(400).json({message: e.message});
}
}
if (obj.type === 'remove_customer') {
try {
const isDeleted = await Customer.deleteOne({userId, _id: obj.id});
return res.send({deleted: true});
} catch(e) {
return res.status(400).json({message: e.message});
}
}
})
module.exports = Router;