1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- 'use strict';
- const crypto = require('crypto');
- const redis = require('redis');
- let client = null;
- const subscriptions = [];
- const lib = {
-
- init: (url, cb) => {
- client = redis.createClient({ url: url });
- client.on('error', (err) => console.error);
- client.on('message', (pattern, channel, expiredKey) => {
- subscriptions.forEach((sub) => {
- if (sub.name !== expiredKey) return;
- sub.cb();
- });
- });
- client.psubscribe('__keyevent@0__:expired');
- cb();
- },
-
- schedule: (name, time, cb) => {
- client.set(crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), '', 'PX', 'NX', time, cb);
- },
-
- subscribe: (name, cb, unique = false) => {
- if (unique && subscriptions.find((subscription) => subscription.name == name)) return;
- let subscription = { name: crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), cb };
- subscriptions.push(subscription);
- return subscription;
- },
-
- remove: (subscription) => {
- let index = subscriptions.indexOf(subscription);
- if (index) subscriptions.splice(index, 1);
- }
- };
- module.exports = lib;
|