-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
index.js
219 lines (173 loc) · 6.14 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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// ***************************************************************************
// Bank API code from Web Dev For Beginners project
// https://github.com/microsoft/Web-Dev-For-Beginners/tree/main/7-bank-project/api
// ***************************************************************************
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
const crypto = require('crypto');
const pkg = require('./package.json');
// App constants
const port = process.env.PORT || 3000;
const apiPrefix = '/api';
// Store data in-memory, not suited for production use!
const db = {
test: {
user: 'test',
currency: '$',
description: `Test account`,
balance: 75,
transactions: [
{ id: '1', date: '2020-10-01', object: 'Pocket money', amount: 50 },
{ id: '2', date: '2020-10-03', object: 'Book', amount: -10 },
{ id: '3', date: '2020-10-04', object: 'Sandwich', amount: -5 }
],
},
jondoe: {
user: 'jondoe',
currency: '$',
description: `Second test account`,
balance: 150,
transactions: [
{ id: '1', date: '2022-10-01', object: 'Gum', amount: -2 },
{ id: '2', date: '2022-10-03', object: 'Book', amount: -10 },
{ id: '3', date: '2022-10-04', object: 'Restaurant', amount: -45 }
],
}
};
// Create the Express app & setup middlewares
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors({ origin: /http:\/\/(127(\.\d){3}|localhost)/}));
app.options('*', cors());
// ***************************************************************************
// Configure routes
const router = express.Router();
// Hello World for index page
app.get('/', function (req, res) {
return res.send("Hello World!");
})
app.get('/api', function (req, res) {
return res.send("Fabrikam Bank API");
})
// ----------------------------------------------
// Create an account
router.post('/accounts', (req, res) => {
// Check mandatory request parameters
if (!req.body.user || !req.body.currency) {
return res.status(400).json({ error: 'Missing parameters' });
}
// Check if account already exists
if (db[req.body.user]) {
return res.status(409).json({ error: 'User already exists' });
}
// Convert balance to number if needed
let balance = req.body.balance;
if (balance && typeof balance !== 'number') {
balance = parseFloat(balance);
if (isNaN(balance)) {
return res.status(400).json({ error: 'Balance must be a number' });
}
}
// Create account
const account = {
user: req.body.user,
currency: req.body.currency,
description: req.body.description || `${req.body.user}'s budget`,
balance: balance || 0,
transactions: [],
};
db[req.body.user] = account;
return res.status(201).json(account);
});
// ----------------------------------------------
// Get all data for the specified account
router.get('/accounts/:user', (req, res) => {
const account = db[req.params.user];
// Check if account exists
if (!account) {
return res.status(404).json({ error: 'User does not exist' });
}
return res.json(account);
});
// ----------------------------------------------
// Remove specified account
router.delete('/accounts/:user', (req, res) => {
const account = db[req.params.user];
// Check if account exists
if (!account) {
return res.status(404).json({ error: 'User does not exist' });
}
// Removed account
delete db[req.params.user];
res.sendStatus(204);
});
// ----------------------------------------------
// Add a transaction to a specific account
router.post('/accounts/:user/transactions', (req, res) => {
const account = db[req.params.user];
// Check if account exists
if (!account) {
return res.status(404).json({ error: 'User does not exist' });
}
// Check mandatory requests parameters
if (!req.body.date || !req.body.object || !req.body.amount) {
return res.status(400).json({ error: 'Missing parameters' });
}
// Convert amount to number if needed
let amount = req.body.amount;
if (amount && typeof amount !== 'number') {
amount = parseFloat(amount);
}
// Check that amount is a valid number
if (amount && isNaN(amount)) {
return res.status(400).json({ error: 'Amount must be a number' });
}
// Generates an ID for the transaction
const id = crypto
.createHash('md5')
.update(req.body.date + req.body.object + req.body.amount)
.digest('hex');
// Check that transaction does not already exist
if (account.transactions.some((transaction) => transaction.id === id)) {
return res.status(409).json({ error: 'Transaction already exists' });
}
// Add transaction
const transaction = {
id,
date: req.body.date,
object: req.body.object,
amount,
};
account.transactions.push(transaction);
// Update balance
account.balance += transaction.amount;
return res.status(201).json(transaction);
});
// ----------------------------------------------
// Remove specified transaction from account
router.delete('/accounts/:user/transactions/:id', (req, res) => {
const account = db[req.params.user];
// Check if account exists
if (!account) {
return res.status(404).json({ error: 'User does not exist' });
}
const transactionIndex = account.transactions.findIndex(
(transaction) => transaction.id === req.params.id
);
// Check if transaction exists
if (transactionIndex === -1) {
return res.status(404).json({ error: 'Transaction does not exist' });
}
// Remove transaction
account.transactions.splice(transactionIndex, 1);
res.sendStatus(204);
});
// ***************************************************************************
// Add 'api` prefix to all routes
app.use(apiPrefix, router);
// Start the server
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});