/
api-under-test.js
106 lines (88 loc) · 2.65 KB
/
api-under-test.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
const express = require("express");
const util = require("util");
const axios = require("axios");
const bodyParser = require("body-parser");
const mailer = require("./libraries/mailer");
const OrderRepository = require("./data-access/order-repository");
let connection;
const initializeWebServer = async (customMiddleware) => {
return new Promise((resolve, reject) => {
// A typical Express setup
expressApp = express();
expressApp.use(
bodyParser.urlencoded({
extended: true,
})
);
expressApp.use(bodyParser.json());
if (customMiddleware) {
expressApp.use(customMiddleware);
}
defineRoutes(expressApp);
// ️️️✅ Best Practice: Specify no port for testing, only in production
const webServerPort = process.env.PORT ? process.env.PORT : null;
connection = expressApp.listen(webServerPort, () => {
resolve(expressApp);
});
});
};
const stopWebServer = async () => {
return new Promise((resolve, reject) => {
connection.close(() => {
resolve();
});
});
};
const defineRoutes = (expressApp) => {
const router = express.Router();
// add new order
router.post("/", async (req, res, next) => {
try {
console.log(`Order API was called to add new Order ${util.inspect(req.body)}`);
// validation
if (!req.body.productId) {
res.status(400).end();
return;
}
// verify user existence by calling external Microservice
const existingUserResponse = await axios.get(`http://localhost/user/${req.body.userId}`, {
validateStatus: false,
});
console.log(`Asked to get user and get response with status ${existingUserResponse.status}`);
if (existingUserResponse.status === 404) {
res.status(404).end();
return;
}
// save to DB (Caution: simplistic code without layers and validation)
const DBResponse = await new OrderRepository().addOrder(req.body);
res.json(DBResponse);
} catch (error) {
next(error);
}
});
// get existing order
router.get("/", (req, res, next) => {
res.json({
a: 1,
});
});
expressApp.use("/order", router);
expressApp.use(async (err, req, res, next) => {
console.log(err);
if (process.env.SEND_MAILS === "true") {
// important notification logic here
await mailer.send('Error', err.message, 'admin@app.com');
// Other important notification logic here
}
res.status(500).end();
});
};
process.on("uncaughtException", () => {
// a log of other logic here
console.log("Error occured!");
});
initializeWebServer();
module.exports = {
initializeWebServer,
stopWebServer,
};