发送推送通知后退出节点脚本

时间:2017-07-28 14:19:06

标签: mysql node.js promise web-push

代码很长但问题可能是基本的。

const webpush = require('web-push');
const argv = require('yargs').argv;
const mysql = require('mysql');
const config = require('./../config.json');
const con = mysql.createConnection({
  host: config.pushNotifications.host,
  user: config.pushNotifications.user,
  password: config.pushNotifications.password,
  database: config.pushNotifications.database
});

con.connect(function(err) {});

return sendNotif();

function sendNotif() {
  const type = argv.type;
  const dataToSend = {
    "title": argv.title,
    "message": argv.message
  };

  return getSubscriptions()
    .then(function(subscriptions) {
      let promiseChain = Promise.resolve();

      for (let i = 0; i < subscriptions.length; i++) {
        let subscription = subscriptions[i];

        let pref = subscription.preferences.split('');

        if (pref[type - 1] == 1) {
          promiseChain = promiseChain.then(() => {
            return triggerPushMsg(subscription, JSON.stringify(dataToSend));
          });
        }
      }
    })
    .catch(function(err) {
      throw new Error(err);
    });
}


function triggerPushMsg(subscription, dataToSend) {
  return webpush.sendNotification(subscription, dataToSend)
    .catch((err) => {
      if (err.statusCode === 410) {
        return deleteSubscriptionFromDatabase(subscription.endpoint);
      } else {
        log.warn('Subscription is no longer valid: ', err);
      }
    });
}

function deleteSubscriptionFromDatabase(endpoint) {
  let sql = 'DELETE FROM subscriptions WHERE endpoint = ?';

  return new Promise(function(resolve, reject) {
    con.query(sql, [endpoint], function(err, result) {
      if (err) {
        throw reject(err);
      }
      log.debug('Deleted successfully from database. endpoint: ', endpoint);
      resolve(true);
    });
  });
}

function getSubscriptions() {
  let sql = 'SELECT * FROM subscriptions';

  return new Promise(function(resolve, reject) {
    con.query(sql, function(err, result) {
      if (err) {
        throw reject(err);
      }
      resolve(result);
    });
  });
}

此代码从MySQL数据库中获取一些订阅并向其发送通知。 我已经跳过了VAPID密钥初始化部分,但我已经在我的程序中正确完成了它,因为它运行正常并且通知已经发送。但问题是,一旦我使用命令 -

运行它
node test/notification-trigger.js --type <type> --title "<title>" --message "<message>"

程序不会自动终止。

这里有什么需要改变的? 感谢您的期待。

0 个答案:

没有答案