/
index.js
89 lines (81 loc) · 2.47 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
'use strict';
const globalHooks = require('../../../hooks');
var validateSchema = require('../../../hooks/validate-schema');
var productSchema = require('../schema');
exports.before = {
all: [],
find: [includeAssociatedModels, findbyCategoryName, findCategoryById, globalHooks.allowNull(), globalHooks.wildcardsInLike()],
get: [includeAssociatedModels],
create: [globalHooks.errorIfReadonly, validateSchema(productSchema)],
update: [globalHooks.errorIfReadonly, validateSchema(productSchema)],
patch: [globalHooks.errorIfReadonly],
remove: [globalHooks.errorIfReadonly]
};
exports.after = {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
};
function includeAssociatedModels (hook) {
if (hook.params.query.$select) return; // if selecting specific columns, do not include
hook.params.sequelize = {
distinct: true, // must set this in order to get correct total count
include: [{
model: hook.app.db.category, as: 'categories', through: {attributes: []}
}]
};
}
function findCategoryById (hook) {
/*
This makes both of these work:
/products?category[id]=abcat0208002
/products?category.id=abcat0208002
*/
let catId;
let q = hook.params.query;
if (q['category.id']) {
catId = q['category.id'];
delete q['category.id'];
} else if (q.category && q.category.id) {
catId = q.category.id;
delete q.category;
}
if (catId) {
q.id = {
// a bit gnarly but works https://github.com/sequelize/sequelize/issues/1869
$in: hook.app.db.Sequelize.literal(`(
SELECT DISTINCT productId from productcategory
INNER JOIN categories on categories.id = productcategory.categoryId
where categories.id = '${catId}')`)
};
}
}
function findbyCategoryName (hook) {
/*
This makes both of these work:
/products?category[name]=Coffee%20Pods
/products?category.name=Coffee%20Pods
*/
let catName;
let q = hook.params.query;
if (q['category.name']) {
catName = q['category.name'];
delete q['category.name'];
} else if (q.category && q.category.name) {
catName = q.category.name;
delete q.category;
}
if (catName) {
q.id = {
// a bit gnarly but works https://github.com/sequelize/sequelize/issues/1869
$in: hook.app.db.Sequelize.literal(`(
SELECT DISTINCT productId from productcategory
INNER JOIN categories on categories.id = productcategory.categoryId
where categories.name = '${catName}')`)
};
}
}