This repository has been archived by the owner on Jun 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OdooApi.js
338 lines (301 loc) · 11.5 KB
/
OdooApi.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
const Logger = require('xvi-logger');
const Helper = require('xvi-helper');
const OdooCoreApi = require('xvi-odooapi-core');
const readDirFiles = require('read-dir-files');
const moment = require('moment-timezone');
const del = require('del');
class OdooApi {
constructor({
name = 'OdooApi',
loggerInstance = false,
url = false,
port = false,
protocol = false,
db = false,
username = false,
password = false,
dateFormat = 'YYYYMMDD HH:mm:ss',
queueTimer = 250,
maxRecordsPerCall = 200,
timezone = "Asia/Hong_Kong",
handler = false,
cacheFolder = false,
cacheTimer = 10000,
cacheLoopTimer = 1000,
cleanCacheLoop = true,
cache = false
}) {
var self = this;
self._arguments = arguments[0]; //store arguments
self._name = name; //name of instance
self._logger = new Logger({
name: self._name,
instance: loggerInstance
});
self._helper = new Helper();
self._callQueueTimer = queueTimer;
self._maxRecordsPerCall = maxRecordsPerCall;
self._protocol = protocol;
self._url = url;
self._port = port;
self._db = db;
self._username = username;
self._password = password;
self._dateFormat = dateFormat;
self._timezone = timezone;
self._cache = cache;
self._cacheTimer = cacheTimer;
self._cacheLoopTimer = 1000;
self._cacheFolder = cacheFolder;
self._cleanCacheLoop = cleanCacheLoop;
self._cacheMemory = {};
self.exportMethodsToHandler(handler);
}
exportMethodsToHandler(handler) {
var self = this;
self._logger.func('exportMethodsToHandler');
handler['gDateFormat'] = function () {
return self.gDateFormat();
}
handler['gTimeZone'] = function () {
return self.gTimeZone();
}
handler['format_many2one'] = function (ids = []) {
return self.format_many2one(ids);
}
handler['updateModel'] = async function (model, item) {
return self.updateModel(model, item);
}
handler['insertModel'] = async function (model, item) {
return self.insertModel(model, item);
}
handler['getModelByFilters'] = async function (model = false, filters = [], fields = ['name'], offset = 0, limit = 100, sorting = false, cached = true, cacheTimer = false) {
return self.getModelByFilters(model, filters, fields, offset, limit, sorting, cached, cacheTimer);
}
handler['executeWorkflow'] = async function (id, model, action, additional = []) {
return self.executeWorkflow(id, model, action, additional);
}
handler['actionModelByFilters'] = async function (action = false, model = false, filters = false, comparefields = false, validateCb = false, compareCb = false) {
return self.actionModelByFilters(action, model, filters, comparefields, validateCb, compareCb);
}
}
async getCache(key = false) {
var self = this;
if (!self._cache)
return false;
if (self._cacheFolder) {
//check for files with this key in this folder
var path = `${self._cacheFolder}/${key}.json`;
try {
var data = await self._helper.readJson(path);
self._logger.debug('Served Cache: ' + key);
return JSON.parse(data);
} catch (err) {
//console.log(err); //do not block
return false;
}
} else {
//cache is in memory, check array
return self._cacheMemory[key] ? self._cacheMemory[key] : false;
}
return false;
}
async getFileList(path = false) {
var self = this;
self._logger.func(`getFileList`);
if (!path)
return false;
return new Promise(res => {
readDirFiles.list(path, function (err, filenames) {
if (err) return console.dir(err);
res(filenames);
});
})
}
async cleanCacheLoop() {
var self = this;
if (!self._cache)
return false;
self._logger.func('cleanCacheLoop');
self._cacheLoop = setInterval(async function () {
self._logger.info('cleanCacheLoop: check');
if (self._cacheFolder) {
try {
//get all files cached
var files = await self.getFileList(self._cacheFolder);
//chck for each if we need to remove
for (var index = 0; index < files.length; index++) {
var path = files[index]; //`${self._cacheFolder}/${key}.json`;
if (self._helper.containsStr('.json', path)) {
try {
var data = await self._helper.readJson(path);
data = JSON.parse(data);
//must remove
if (moment().diff(moment(data.date), 'ms') > data.expiration) {
await del.sync([path]);
//self._logger.debug('Removed Cache after ' + (data.expiration / 1000) + 's : ' + data.key);
}
} catch (err) {
// console.log(err); //do not block
//return false;
}
}
}
return true;
} catch (err) {
//console.log(err) //do not block
//self._logger.debug('Cannot remove cache: ' + key);
return false;
}
} else {
Object.keys(self._cacheMemory).map(k => {
try {
if (moment().diff(moment(self._cacheMemory[k].date), 'ms') > self._cacheMemory[k].expiration) {
// self._logger.debug('Removed Cache after ' + (self._cacheMemory[k].expiration / 1000) + 's : ' + self._cacheMemory[k].key);
delete self._cacheMemory[k];
}
} catch (err) {
// console.log(err); //do not block
}
});
return true;
}
}, self._cacheLoopTimer)
return true;
}
async cleanAllCache() {
var self = this;
if (!self._cache)
return false;
self._logger.func('cleanAllCache');
if (self._cacheFolder) {
try {
//get all files cached
var files = await self.getFileList(self._cacheFolder);
for (var index = 0; index < files.length; index++) {
var path = files[index]; //`${self._cacheFolder}/${key}.json`;
if (self._helper.containsStr('.json', path)) {
try {
await del.sync([path]);
} catch (err) {
// console.log(err); //do not block
//return false;
}
}
}
} catch (err) {
// console.log(err)
}
} else {
self._cacheMemory = {};
}
return true;
}
async setCache(key, data = false, expiration = false) {
var self = this;
if (!self._cache || !data)
return false;
var expiration = expiration ? expiration : self._cacheTimer;
// self._logger.func('setCache', key);
if (self._cacheFolder) {
//write in file
var path = `${self._cacheFolder}/${key}.json`;
await self._helper.writeJson(path, JSON.stringify({
date: moment().format(),
key: key,
expiration: expiration,
data: data
}));
} else {
//cache is in memory, check array
self._cacheMemory[key] = {
date: moment().format(),
key: key,
expiration: expiration,
data: data
};
}
return true;
}
gDateFormat() {
var self = this;
return self._dateFormat;
}
gTimeZone() {
var self = this;
return self._timezone;
}
format_many2one(ids = []) {
return (ids.length > 0) ? [4, ids] : false;
}
async initialize() {
var self = this;
self._logger.func('initialize')
self._odooApi = new OdooCoreApi({
name: `CAPI`,
loggerInstance: self._logger,
url: self._url,
port: self._port,
protocol: self._protocol,
db: self._db,
username: self._username,
password: self._password,
dateFormat: self._dateFormat,
queueTimer: self._queueTimer,
maxRecordsPerCall: self._maxRecordsPerCall
});
if (self._cleanCacheLoop) {
await self.cleanCacheLoop();
await self.cleanAllCache();
}
await self._odooApi.initialize();
}
//METHODS FROM ODOOCORE API
//UPDATE ANY MODEL IN DB DEPENDING ON USER RIGHTS
async updateModel(model, item) {
var self = this;
// self._logger.func('updateModel', model);
return self._odooApi.updateModel(model, item);
}
//INSERT ANY MODEL IN DB DEPENDING ON USER RIGHTS
async insertModel(model, item) {
var self = this;
//self._logger.func('insertModel', model);
return self._odooApi.insertModel(model, item);
}
//GET ANY MODEL IN DB DEPENDING ON USER RIGHTS
async getModelByFilters(model = false, filters = [], fields = ['name'], offset = 0, limit = 100, sorting = false, cached = false, cacheTimer = false) {
var self = this;
// self._logger.func(`getModelByFilters`, `${model}`); //${JSON.stringify(filters)}
if (self._cache && cached) {
var key = self._helper.md5(JSON.stringify({
model: model,
filters: filters,
fields: fields,
offset: offset,
limit: limit,
sorting: sorting
}));
var cache = await self.getCache(key);
if (cache)
return cache;
var data = await self._odooApi.getModelByFilters(model, filters, fields, offset, limit, sorting);
await self.setCache(key, data, cacheTimer);
return data;
} else {
return self._odooApi.getModelByFilters(model, filters, fields, offset, limit, sorting);
}
}
//Execute workflow
async executeWorkflow(id, model, action, additional = []) {
var self = this;
// self._logger.func('execute', `${action} on ${model}#${id}`);
return self._odooApi.executeWorkflow(id, model, action, additional);
}
async actionModelByFilters(action = false, model = false, filters = false, comparefields = false, validateCb = false, compareCb = false) {
var self = this;
//self._logger.func(`actionModelByFilters`, `${action} ${model} matching ${JSON.stringify(filters)}`);
return self._odooApi.actionModelByFilters(action, model, filters, comparefields, validateCb, compareCb)
}
}
module.exports = OdooApi;