具有异步功能的Sailsjs策略

时间:2018-06-15 19:58:06

标签: javascript node.js async-await sails.js

我尝试做的是将sailsjs应用程序的快速实施作为策略。

因此我注册了政策bruteForce。

我的bruteForce.js文件包含:

const ExpressBrute = require('express-brute'),
  moment = require('moment'),
  SequelizeStore = require('express-brute-sequelize'),
  Sequelize = require('sequelize');

const failCallback = (req, res, next, nextValidRequestDate) =>  {
  res.status(429).json({
    message: 'You\'ve made too many failed attempts in a short period of time, please try again '+moment(nextValidRequestDate).fromNow(),
    nextValidRequestDate,
    tryAgainIn: moment(nextValidRequestDate).diff(moment)
  })
}

const handleStoreError = (error) => {
  sails.log.error(error);
  throw {
    message: error.message,
    parent: error.parent
  };
}

const store = new ExpressBrute.MemoryStore();

const bruteForceOptions = {
  freeRetries: 3,
  minWait: 1000*60,
  maxWait: 1000*60*15,
  failCallback,
  handleStoreError
}

const bruteforce = new ExpressBrute(store, bruteForceOptions)

module.exports = async function (req, res, next) {
  return bruteforce.prevent(req, res, next)
};

到目前为止这是有效的,但是当我尝试设置另一个商店驱动程序时 - 我现在选择了Sequelize驱动程序。

因此我补充说:

const sequelize = new Sequelize('table', 'root', 'secret', {
  host: '127.0.0.1',
  dialect: 'mysql',
  operatorsAliases: false,
  logging: sails.log.debug
});

const getBruteforce = async function(){
  new SequelizeStore(sequelize, 'bruteStore', {}, function(store) {
    console.log(store)
    return new ExpressBrute(store, bruteForceOptions)
  });
}

我的新政策功能是:

module.exports = async function (req, res, next) {
  const bruteforce = await getBruteforce()
  return bruteforce.prevent(req, res, next)
};

但是在这里我总是得到错误bruteforce undefined,然后在新SequelizeStore的回调中调用console.log。

我不明白我是如何解决的。

有人有想法吗?

1 个答案:

答案 0 :(得分:1)

因为您的WKWebView函数实际上没有返回任何内容。

getBruteforce()

执行此操作:

const getBruteforce = async function(){
  new SequelizeStore(sequelize, 'bruteStore', {}, function(store) {
    console.log(store)
    // Below returns from the callback, **not** the async function
    return new ExpressBrute(store, bruteForceOptions)
  });
}

我建议您阅读有关如何return values from async functions的内容。