承诺结构 - 我这样做对吗?

时间:2017-11-11 10:04:49

标签: javascript node.js

我目前正在构建一个node.js项目,以根据我的中间件调用加载用户配置文件。目前我刚刚开始使用promises,而且我现在已经达到了嵌套的promise数据,但我觉得我正在实现它们,就像我对回调地狱结构一样。

我的中间件:

const { mount } = require('telegraf');
const log = require('../Utilities/Log')
const Authenticator = require('../User/Authenticator')

/* eslint no-param-reassign: ["error", { "props": false }] */
module.exports = () => mount('text', (ctx, next) => {
  // Attempt to login the user given their ID
  Authenticator.login(ctx.from.id, ctx.from).then((userObject) => {
    // Returned user is attached to the context state to pass through middleware
    ctx.state.user = userObject;
    log.debug(ctx.state.user)
    // Continue with the attached user object through rest of middleware
    return next();
  }).catch((err) => {
    // Do not send a next() as we have hit an error.
    return log.error(err)

  })
});

使用登录方法的身份验证器:

const User = require('../User/User')

class Authenticator {
    static login(userID = 0, userFrom = {}) {
        return new Promise ((resolve, reject) => {
            User.getUserByID(userFrom.id).then((userRecord) => {
                let result = {}
                if (!userRecord) {
                    result = new User('', userFrom.first_name, userFrom.username, '', userID)
                } else {

                    result = new User(userRecord._pNick, userRecord._firstName, userRecord._userName, userRecord._phoneNumber, userID)
                }             
                return resolve(result)
            }).catch((err) => {
                return reject(err)
            })
        })
    }
}

我的用户类,包含从数据库中检索的方法

const dbConnection = require('../Services/db/Db')
const config = require('../Config')
const USER_COLLECTION = config.databaseConnection.DB_USER_COLLECTION

// Set database connection to use the User table
const userTable = dbConnection.collection(USER_COLLECTION)

class User {
    constructor(pNick = '', firstName = '', userName = '', phoneNumber = '', userIdentifier = 0) {
        this._pNick = pNick
        this._firstName = firstName
        this._userName = userName
        this._phoneNumber = phoneNumber
        this._userID = userIdentifier
        this._isAdmin = this.isAdmin()
    }

    static getUserByID(userID = 0) {
        return new Promise( (resolve, reject) => {
            userTable.findOne({
            _userID: userID
        }, (err, user) => {
            if (err) {
                return reject(err)
            }
            return resolve(user)
        })
    })
    }

    isAdmin () {
        if (this._userID === config.adminUser.ADMIN_ID) {
            return true
        }
        return false
    }

    isAuthenticated () {
        if (this._pNick.length() > 1) {
            return true
        }
        return false
    }

}

module.exports = User

感觉好像我可以在某种程度上扁平化这种结构?

0 个答案:

没有答案