product_cache.js
2.93 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
90
91
92
93
94
95
96
97
98
/**
*
* @author: chenfeng<feng.chen@yoho.cn>
* @date: 16/10/20
*/
import Model from './model';
import rp from 'request-promise';
import ws from '../../lib/ws';
class ProductCache extends Model{
constructor() {
super('product_cache');
}
async removePriceCache(list) {
let self = this;
let apis = await self.findAll();
if (!apis.length) {
return;
}
let url = apis[0].priceCacheApi;
self._broadcast(`开始提交:批量变价`);
await self._batchPost(list, url);
}
async removeProductCache(list) {
let self = this;
let apis = await self.findAll();
if (!apis.length) {
return;
}
let url = apis[0].productCacheApi;
self._broadcast(`开始提交:其它批量`);
await self._batchPost(list, url);
}
async _batchPost(list, url) {
let self = this;
let interval = 50;
return new Promise(async (resolve, reject) => {
let tick = parseInt(list.length / interval, 10) + (list.length % interval > 0 ? 1 : 0);
let post = async (i, len) => {
if (i < len) {
let limit = list.length > (i + 1) * interval ? (i + 1) * interval : list.length;
let datas = list.slice(i * interval, limit);
try {
await self._postApi(datas, url);
self._broadcast(`进度:${limit}/${list.length}`)
} catch(err) {
self._broadcast(`错误:${err.message}`)
}
setTimeout(async () => {
await post(++i, tick);
}, 500);
} else {
self._broadcast(`提交完成!`);
resolve();
}
}
await post(0, tick);
});
}
async _postApi(data, url) {
return new Promise((resolve, reject) => {
rp({
method: 'POST',
uri: url,
body: data,
json: true
})
.then(function (res) {
res.code === 200 ? resolve(res) : reject(res);
})
.catch(function (err) {
console.log(err.response.body);
reject(err.response.body)
});
})
}
_broadcast(message) {
console.log(message)
ws.broadcast(`/product_cache/log`, {
message: message
});
}
async init() {
let count = await this.count({});
if (count === 0) {
await this.insert({
priceCacheApi: 'http://service-test3.yohops.com:9999/erp/clear/batch/productPriceCache',
productCacheApi: 'http://service-test3.yohops.com:9999/erp/clear/batch/productCache'
});
}
}
}
export default ProductCache;