-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtpl_sender.js
71 lines (62 loc) · 2.47 KB
/
tpl_sender.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
'use strict';
require('./lib/polyfill');
const path = require('path');
const morgan = require('morgan');
const mongoose = require('mongoose');
const config = require('./lib/config');
const Cache = require('./lib/service/Cache');
const Wechat = require('./lib/service/Wechat');
Cache.init(config.redis);
Wechat.init(config.wechat);
const app = {};
app.config = config;
const Mongo = require('./lib/service/Mongo');
Mongo.getClient(config.mongodb).then((mongoClient) => {
app.db = mongoClient;
require('./lib/model')(app, mongoose);
const interval = 5000;
const limitCount = 10;
const async = require('async');
const LogModel = app.db.models.TemplateSendLog;
setInterval(function() {
// 检查队列中是否仍有 Queuing 任务,有则跳过该次循环
LogModel.count({ status: 'Queuing' }).exec((err, count) => {
if(err) return console.error(err);
if(count > 0) return console.log(`Already Queuing: ${count}`);
// 取出 limitCount 条 Pending 的任务,改为 Queuing
LogModel.find({ status: 'Pending' }).populate('templateMessage subscriber').limit(limitCount).exec((err, logs) => {
if(err) return console.error(err);
if(!logs || !logs.length) return console.log(`Empty Queue.`);
// 将取出 logs 的状态改为 Queuing
LogModel.update({ _id: { $in: logs.map((log) => (log._id)) } }, { status: 'Queuing' }, { multi: true }).exec((err) => {
if(err) return console.error(err);
// 只有 10 条,并行发送
async.each(logs, function(log, callback) {
console.log(`Send Template Message: OpenId=${log.subscriber.openId} tplId=${log.templateMessage.templateId}`);
Wechat.sendTemplateMessage(
log.subscriber.openId,
log.templateMessage.templateId,
log.templateMessage.url,
log.templateMessage.data
).then((data) => {
log.status = 'Sending';
log.msgId = String(data.msgid);
log.save(callback);
}).catch((err) => {
log.status = err.message || 'Unknown error';
log.save(callback);
});
}, function(err) {
if(err) {
console.error(`Error: ${err}`);
console.error(err && err.stack);
} else {
console.log(`Send: ${logs.length}`);
}
});
});
});
});
}, interval);
console.log(`Started.`);
});