-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.js
More file actions
89 lines (87 loc) · 2.7 KB
/
index.js
File metadata and controls
89 lines (87 loc) · 2.7 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
81
82
83
84
85
86
87
88
89
const helper = require('think-helper');
const path = require('path');
const {COMPARISON_LIST} = require('think-model-abstract');
const Model = require('./lib/model.js');
const DB_CONNECTION = Symbol('db_connection');
module.exports = app => {
app.on('filterParam', data => {
for (const name in data) {
// ['EXP', 2]
if (helper.isArray(data[name]) && helper.isString(data[name][0])) {
if (COMPARISON_LIST.indexOf(data[name][0].toUpperCase()) > -1) {
data[name][0] += ' ';
}
} else if (helper.isObject(data[name])) { // {EXP: 2}
const result = {};
for (const key in data[name]) {
if (COMPARISON_LIST.indexOf(key.toUpperCase()) > -1) {
result[`${key} `] = data[name][key];
} else {
result[key] = data[name][key];
}
}
data[name] = result;
}
}
});
function model(name, config, m = 'common') {
const models = app.modules.length ? (app.models[m] || {}) : app.models;
const Cls = models[name] || Model;
const modelName = name ? path.basename(name) : name;
const instance = new Cls(modelName, config);
// add models in config, it's need in model when get relation model instance
instance.models = models;
return instance;
};
/**
* inject model method
* @param {String} name
* @param {Object} config
* @param {String} m
*/
function injectModel(name, config, m) {
const modelConfig = app.think.config('model', undefined, m);
const cacheConfig = app.think.config('cache', undefined, m);
config = helper.parseAdapterConfig(modelConfig, config);
const instance = model(name, config, m);
instance._cacheConfig = cacheConfig;
return instance;
}
return {
think: {
Model: Model,
model: injectModel
},
service: {
model: injectModel
},
controller: {
model(name, config, m) {
return this.ctx.model(name, config, m);
},
transModel(name, config, m) {
return this.ctx.transModel(name, config, m);
}
},
context: {
model(name, config, m = this.module) {
config = helper.parseAdapterConfig(this.config('model'), config);
const instance = model(name, config, m);
// add adapter cache config
instance._cacheConfig = this.config('cache');
if (config.reuseDB) {
if (this[DB_CONNECTION]) {
instance.db(this[DB_CONNECTION]);
} else {
this[DB_CONNECTION] = instance.db();
// when response end, release db connection
this.res.once('end', () => {
this[DB_CONNECTION] = null;
});
}
}
return instance;
}
}
};
};