-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverQueriesResolver.js
64 lines (56 loc) · 1.65 KB
/
serverQueriesResolver.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
const paginateQuery = (query, page = 1, pageSize = 5) =>
query.drop((page - 1) * pageSize).take(pageSize);
const product = ({ id }, { db }) => db.get("products").getById(id).value();
const products = ({ category }, { db }) => ({
totalSize: () =>
db
.get("products")
.filter((p) =>
category ? new RegExp(category, "i").test(p.category) : p
)
.size()
.value(),
products: ({ page, pageSize, sort }) => {
let query = db.get("products");
if (category) {
query = query.filter((item) =>
new RegExp(category, "i").test(item.category)
);
}
if (sort) {
query = query.orderBy(sort);
}
return paginateQuery(query, page, pageSize).value();
},
});
const categories = (args, { db }) => db.get("categories").value();
const resolveProducts = (products, db) =>
products.map((p) => ({
quantity: p.quantity,
product: product({ id: p.product_id }, { db }),
}));
const resolveOrders = (onlyUnshipped, { page, pageSize, sort }, { db }) => {
let query = db.get("orders");
if (onlyUnshipped) {
query = query.filter({ shipped: false });
}
if (sort) {
query = query.orderBy(sort);
}
return paginateQuery(query, page, pageSize)
.value()
.map((order) => ({
...order,
products: () => resolveProducts(order.products, db),
}));
};
const orders = ({ onlyUnshipped = false }, { db }) => ({
totalSize: () =>
db
.get("orders")
.filter((o) => (onlyUnshipped ? o.shipped === false : o))
.size()
.value(),
orders: (...args) => resolveOrders(onlyUnshipped, ...args),
});
module.exports = { product, products, categories, orders }