-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery2.js
54 lines (48 loc) · 1.27 KB
/
query2.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
import 'dotenv/config';
import { Client, fql } from "fauna";
const client = new Client({
secret: process.env.FAUNADB_SECRET,
endpoint: process.env.FAUNA_ENDPOINT
});
const customerId = "101";
const cart = [
{ productId: "201", quantity: 10 },
{ productId: "202", quantity: 11 }
];
try {
const query = fql`
${cart}.forEach(x=>{
let p = product.byId(x.productId)!
let updatedQty = p.quantity - x.quantity
if (updatedQty < 0) {
abort("Insufficient stock for product " + p.name + ": Requested quantity=" + x.quantity.toString())
} else {
p.update({
quantity: updatedQty
})
}
})
let cust = customer.byId(${customerId})!
order.create({
name: "Order for " + cust.firstName,
customer: cust,
creationDate: Time.now(),
status: 'processing',
orderProducts: ${cart}.map(x=>{
product: product.byId(x.productId),
quantity: x.quantity,
price: product.byId(x.productId)!.price
}),
deliveryAdress: cust.address,
creditCard: cust.creditCard
}) {
id,
creationDate
}
`;
const res = await client.query(query);
console.log(res);
client.close();
} catch (err) {
console.log(err)
}