-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (67 loc) · 2.31 KB
/
index.js
File metadata and controls
76 lines (67 loc) · 2.31 KB
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
const fastify = require('fastify')({ logger: { level: 'trace' } })
const crypto = require('crypto')
const {MongoClient} = require('mongodb');
const {default: axios} = require('axios');
const {getTotalPrice, pay} = require("./orders");
const mongoHost = process.env.MONGO_HOST
const mongoPort = process.env.MONGO_PORT ?? 27017
const mongoClient = new MongoClient(`mongodb://${mongoHost}:${mongoPort}/orders`)
let ordersCollection;
const paymentsURL = process.env.PAYMENTS_URL
const catalogURL = process.env.CATALOG_URL
const metricsURL = process.env.METRICS_URL
async function bootstap() {
try {
await mongoClient.connect();
ordersCollection = mongoClient.db('orders').collection('orders');
await fastify.listen(3000, '0.0.0.0')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
fastify.post('/orders', async function (request, reply) {
const { items } = request.body;
const order = { id: crypto.randomUUID(), items: items, state: 'pre-validation' }
if (!Array.isArray(items) || items.some(item => typeof item !== 'string')) {
order.state = 'invalid'
ordersCollection.insertOne(order);
reply.send(order.state).code(400);
return;
}
const totalPrice = await getTotalPrice(items)
console.log(totalPrice)
if (totalPrice < 0) {
order.state = 'invalid'
ordersCollection.insertOne(order);
reply.send(order.state).code(400);
return;
}
order.state = 'pre-payment'
if (!(await pay({amount: totalPrice, orderId: order.id}))) {
order.state = 'payment-failed'
ordersCollection.insertOne(order);
reply.send(order.state).code(400);
return;
}
order.state = 'landed'
ordersCollection.insertOne(order);
reply.send(order.state).code(200);
await axios.put('http://metrics:3000/updateMetrics')
})
fastify.get('/orders', async function (request, reply) {
const orders = [];
const cursor = await ordersCollection.find()
await cursor.forEach((order) => orders.push(order))
reply.send(orders).code(200);
})
fastify.get('/healthz', async function(request, reply) {
try {
await axios.get(`${catalogURL}/healthz`)
await axios.get(`${paymentsURL}/healthz`)
return reply.send("Ready").code(200);
} catch (ex) {
reply.send("Failed checking catalog & payments").code(400)
}
})
bootstap()