-
Notifications
You must be signed in to change notification settings - Fork 0
/
dtqueue.js
101 lines (93 loc) · 2.67 KB
/
dtqueue.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
'use strict';
const dtbase = require('./dtbase.js');
const { libs } = require('./dtlibs.js');
const readFile = libs.dtreadfile;
const writeFile = libs.dtwritefile;
const Queue = libs.concurrentQueueThenable;
const dtPath = __dirname.concat('/database/');
const updateInsert = (data, sourceName) => new Promise((resolve, reject) => {
const str = JSON.stringify(data);
const filePath = `${dtPath}${sourceName}.json`;
writeFile(filePath, str)
.then(response => {
resolve('ok');
}).catch(err => {
reject(err);
});
});
const methodSerializer = {
select: data => Promise.resolve(data),
update: updateInsert,
insert: updateInsert,
delete: updateInsert
};
const job = async (element, callback) => {
const { task, thenable } = element;
const { methodName, fn, sourceName, options } = task;
readFile(`${dtPath}${sourceName}.json`)
.then(data => {
if(data) {
const parsedData = JSON.parse(data);
const opt = {
methodName,
fn,
source: parsedData,
options
};
dtbase(opt)
.then(data => {
//работаем с данными
const serializedMethod = methodSerializer[methodName];
serializedMethod(data, sourceName)
.then(data => {
if (data) {
callback(null, { data, thenable });
} else {
callback(err, { thenable });
}
}).catch(err => {
callback(err, { thenable });
})
}, err => {
//работаем с ошибками
//console.log(err);
callback(err, { thenable });
}).catch(err => {
//работаем с ошибками
callback(err, { thenable });
//console.log(err);
})
}
}, err => {
//работаем с ошибками
//console.log(err);
callback(err, { thenable });
}).catch(err => {
//работаем с ошибками
callback(err, { thenable });
//console.log(err);
})
};
const q1 = new Queue(1)
.process(job)
// .wait(4000)
// .timeout(5000)
.success(result => {
const { thenable, data } = result;
thenable.resolve(data);
})
.failure((err, data) => {
const { thenable } = data;
thenable.reject(err);
});
const dtqueue = (methodName, fn, sourceName, options) => new Promise((resolve, reject) => {
q1.add({ methodName, fn, sourceName, options })
.then(result => {
//working with result
resolve(result);
}, err => {
//working with err
reject(err);
});
});
module.exports = dtqueue;