-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
161 lines (142 loc) · 3.94 KB
/
app.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
require("dotenv").config();
const express = require("express"),
mongoose = require("mongoose"),
jwt = require("jsonwebtoken"),
cors = require("cors"),
bcrypt = require("bcrypt"),
User = require("./models/user"),
Debtor = require("./models/debtor"),
auth = require("./middlewares/auth"),
app = express();
app.use(express.json());
mongoose.connect(process.env.DATABASEURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
app.use(cors());
app.post("/api/signup", async (req, res) => {
const user = new User(req.body);
try {
let newUser = await user.save();
if (!newUser) {
throw new Error("Username already exists");
}
const token = jwt.sign({ userid: user._id }, process.env.USERKEY);
res.status(201).send({ token, username: user.username });
} catch (e) {
res.status(400).send(e.message);
}
});
app.post("/api/login", async (req, res) => {
let username = req.body.username;
let password = req.body.password;
try {
if (!username || !password) {
throw new Error("Must provide Username or Password");
}
let user = await User.findOne({ username });
if (!user) {
throw new Error("Invalid Username or Password");
}
let flag = await bcrypt.compare(password, user.password);
if (!flag) {
throw new Error("Invalid Username or Password");
}
const token = jwt.sign({ userId: user._id }, process.env.USERKEY);
res.send({ token, username: user.username });
} catch (e) {
res.status(400).send(e.message);
}
});
app.get("/api/debtors", auth, async (req, res) => {
const match = {};
if (req.query.isDebtFree) {
match.isDebtFree = req.query.isDebtFree === "true";
}
try {
await req.user
.populate({
path: "debtors",
match,
})
.execPopulate();
res.send(req.user.toJSON());
} catch (e) {
res.status(500).send();
}
});
app.post("/api/debtors/new", auth, async (req, res) => {
let isDebtFree = true;
let breakdown = [];
if (req.body.amount > 0) {
let today = new Date();
isDebtFree = false;
const breakdownItem = {
id: mongoose.Types.ObjectId(),
amount: req.body.amount,
type: "previouslyOwed",
date: `${today.getDate()}/${today.getMonth() + 1}/${today.getFullYear()}`,
};
breakdown.push(breakdownItem);
}
const debtor = new Debtor({
...req.body,
isDebtFree,
breakdown,
});
try {
await debtor.save();
req.user.debtors.push(debtor._id);
req.user.save();
res.status(201).send(debtor);
} catch (e) {
res.status(400).send(e.message);
}
});
app.post("/api/debtors/:id/new", auth, async (req, res) => {
let today = new Date();
try {
const { breakdownData } = req.body;
breakdownData["date"] = `${today.getDate()}/${
today.getMonth() + 1
}/${today.getFullYear()}`;
let debtor = await Debtor.findById(req.params.id);
const updatedBreakdown = [...debtor.breakdown, breakdownData];
debtor.breakdown = updatedBreakdown;
let newAmountOwed =
breakdownData.type === "paid"
? debtor.amount - breakdownData.amount
: debtor.amount + breakdownData.amount;
if (newAmountOwed < 0 || newAmountOwed === 0) {
newAmountOwed = 0;
isDebtFree = true;
} else {
isDebtFree = false;
}
debtor.amount = newAmountOwed;
debtor.isDebtFree = isDebtFree;
debtor.save();
res.send(debtor);
} catch (e) {
res.status(400).send(e.message);
}
});
app.delete("/api/debtors/:id", auth, async (req, res) => {
try {
const debtor = await Debtor.findOneAndDelete({ _id: req.params.id });
const newDebtors = req.user.debtors.filter((d) => d != req.params.id);
req.user.debtors = newDebtors;
req.user.save();
if (!debtor) {
res.status(404).send();
}
res.send(debtor);
} catch (e) {
res.status(500).send();
}
});
app.listen(process.env.PORT, () => {
console.log("Listening...... ");
});