Mailspring/api/routes/delta.js

32 lines
1,012 B
JavaScript
Raw Normal View History

2016-06-22 06:57:50 +08:00
const DeltaStreamQueue = require(`${__base}/core/delta-stream-queue`);
2016-06-22 07:32:11 +08:00
function findParams(queryParams = {}) {
const since = new Date(queryParams.since || Date.now())
return {where: {createdAt: {$gte: since}}}
}
2016-06-22 06:57:50 +08:00
module.exports = (server) => {
server.route({
method: 'GET',
path: '/delta/streaming',
handler: (request, reply) => {
const outputStream = require('stream').Readable();
outputStream._read = () => { return };
2016-06-22 08:10:34 +08:00
const sendMsg = (msg = "\n") => outputStream.push(msg);
2016-06-22 06:57:50 +08:00
request.getAccountDatabase()
.then((db) => {
2016-06-22 07:32:11 +08:00
return db.Transaction.findAll(findParams(request.query))
.then((transactions = []) => {
2016-06-22 08:10:34 +08:00
transactions.map(JSON.stringify).forEach(sendMsg);
DeltaStreamQueue.subscribe(db.accountId, sendMsg)
2016-06-22 06:57:50 +08:00
})
}).then(() => {
2016-06-22 08:10:34 +08:00
const keepAlive = setInterval(sendMsg, 1000);
2016-06-22 06:57:50 +08:00
request.on("disconnect", () => { clearTimeout(keepAlive) })
return reply(outputStream)
})
},
});
};