This repository has been archived by the owner on Feb 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathqueryGenerator.ts
103 lines (82 loc) · 2.51 KB
/
queryGenerator.ts
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
import * as R from 'ramda';
import identifiers from './modelIdentifiers';
import {IdentifierMap} from '../pathGenerator';
const validator = require('validator');
const generator = module.exports.generator = function generator(sequelize, history, context, queryAcc?) {
let first = history.shift();
// throw first;
let q = {
model: sequelize.models[first.model]
};
if (queryAcc) {
if (context.query.embed && context.query.embed[queryAcc.model.name]) {
delete context.query.embed[queryAcc.model.name];
}
else {
queryAcc.attributes = [];
}
q['include'] = [queryAcc];
}
let where = {};
if (context.identifiers && context.identifiers[first.identifier]) {
let modelIds: IdentifierMap = identifiers(sequelize.models[first.model]);
Object.keys(modelIds).forEach((id) => {
let _id = context.identifiers[first.identifier];
if (modelIds[id] === 'INTEGER' && validator.isInt(String(_id))) {
modelIds[id] = Number(_id);
}
else if (modelIds[id] === 'UUID' && validator.isUUID(String(_id))) {
modelIds[id] = _id;
}
else if (modelIds[id] !== 'INTEGER' && modelIds[id] !== 'UUID') {
modelIds[id] = String(_id);
}
else {
delete modelIds[id];
}
});
if (Object.keys(modelIds).length === 1) {
where = modelIds;
}
else {
where['$or'] = modelIds;
}
}
if (Object.keys(where).length !== 0) {
q['where'] = where;
}
if (history.length === 0) {
if (context.query.embed && Object.keys(context.query.embed).length > 0) {
let remainingToEmbed = [];
Object.keys(context.query.embed).forEach((model) => {
remainingToEmbed.push({
model: sequelize.models[model]
});
});
q['include'] = R.concat(q['include'] || [], remainingToEmbed);
}
if (context.query.attributes) {
q['where'] = R.merge(context.query.attributes, q['where']);
}
if (context.query.pagination) {
q = R.merge(context.query.pagination, q);
}
if (context.method === 'put' || context.method === 'post') {
q['returning'] = true;
}
return q;
}
else {
return generator(sequelize, history, context, q);
}
};
/**
* Generates queries for sequelize
* @param {relationSchema} relations
* @param {object} params
* @returns The generated query
*/
module.exports = R.curry(function queryGenerator(sequelize, pathHistory, context) {
let history = R.clone(pathHistory);
return generator(sequelize, history, context);
});