-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathOnExecuteNestedQueryable.js
More file actions
80 lines (77 loc) · 3.57 KB
/
OnExecuteNestedQueryable.js
File metadata and controls
80 lines (77 loc) · 3.57 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
77
78
79
80
// MOST Web Framework 2.0 Codename Blueshift BSD-3-Clause license Copyright (c) 2017-2021, THEMOST LP All rights reserved
// eslint-disable-next-line no-unused-vars
const { DataEventArgs } = require('./types');
require('@themost/promise-sequence');
class OnExecuteNestedQueryable {
beforeExecute(event, callback) {
OnExecuteNestedQueryable.prototype.beforeExecuteAsync(event).then(function() {
return callback();
}).catch(function(err) {
return callback(err);
});
}
/**
* @param {DataEventArgs} event
*/
beforeExecuteAsync(event) {
const query = event.emitter && event.emitter.query;
const context = event.model.context;
if (query == null) {
return Promise.resolve();
}
if (Object.prototype.hasOwnProperty.call(query, '$expand')) {
/**
* @type {{ $entity:{ model:string }} | Array<{ $entity:{ model:string }}>}
*/
const expand = query.$expand;
// exit if expand is null or undefined
if (expand == null) {
return Promise.resolve();
}
if (Array.isArray(expand)) {
const sources = expand.map(function(item) {
return function() {
if (item.$entity && item.$entity.model) {
// get nested model
const model = context.model(item.$entity.model);
// if model exists and it's different from the current model
if (model != null && event.model.name !== model.name) {
// try to upgrade
return model.migrateAsync();
}
if (model == null) {
// try to find if the given model is a pre-defined many-to-many association
const attribute = event.model.attributes.filter((attr) => attr.many).find((attr) => {
const mapping = event.model.inferMapping(attr.name);
return mapping && mapping.associationAdapter === item.$entity.model;
});
if (attribute) {
/**
* use DataObjectJunction class as a helper for creating model
* (get an instance of DataObjectJunction class using DataObject.property() method)
* @type {import('./data-object-junction').DataObjectJunction}
*/
const junction = event.model.convert({}).property(attribute.name);
return junction.getBaseModel().migrateAsync();
}
}
}
return Promise.resolve();
}
});
return Promise.sequence(sources);
} else if (expand && expand.$entity && expand.$entity.model) {
// get nested model
const model = context.model(expand.$entity.model);
if (model != null && event.model.name !== model.name) {
// try to upgrade
return model.migrateAsync();
}
}
}
return Promise.resolve();
}
}
module.exports = {
OnExecuteNestedQueryable
}