如何在nodejs中设置sequelize orm

时间:2016-01-11 12:11:54

标签: node.js orm sequelize.js

在模型中:

var Sequelize = require('sequelize');
var sequelize_config = {
      "username": process.env.DB_USERNAME || "root",
      "password": process.env.DB_PASSWORD || "",
      "pool": 200,
      "database": "faasos_platform", 
      "host": "localhost",
      "dialect": "mysql",
      "dialectOptions": {
        "multipleStatements": true
      },
      "logging": true,
      "define": {
        "timestamps": true,
        "underscored": true
      }
    }

var sequeliz = new Sequelize(sequelize_config.database, sequelize_config.username, sequelize_config.password, sequelize_config);

module.exports = function (sequeliz, DataTypes) {
  var auth = sequeliz.define("auth", {
    device_id: {
      type: DataTypes.STRING(50),
      validate: {
        notEmpty: true
      }
    },
    customer_id: {
      type: DataTypes.INTEGER,
      validate: {
        notEmpty: true
      }
    },
    created_at: {
      type: DataTypes.DATE,
      validate: {
        notEmpty: true
      }
    },
    access_token: {
      type: DataTypes.STRING(455),
      validate: {
        notEmpty: true
      }
    },
    ip_address: {
      type: DataTypes.STRING(20),
      validate: {
        notEmpty: true
      }
    },
    is_active: {
      type: DataTypes.INTEGER,
      validate: {
        notEmpty: true
      }
    }
  }, {
    classMethods: {
      associate: function (models) {},
      verify_user: function (req, callback) { 
        var d = new Date();
        var sql = " Select customer_id From auth WHERE access_token =:access_token && is_active = '1' ";
        sequelize.query(sql, {
          replacements: { 
            access_token: req.access_token 
          },
          raw: true
        }).spread(function (data, metadata) {
          callback(null, data);
        }).catch(function (err) {
          callback(err, null);
        });  
      },
      revoke_access_token: function (req, callback) {  
        var sql = "UPDATE  auth SET is_active = 0 " +
          "WHERE customer_id = :customer_id";
        sequelize.query(sql, {
          replacements: { 
            customer_id: req.id
          },
          raw: true
        }).spread(function (data, metadata) {
          callback(null, data);
        }).catch(function (err) {
          callback(err, null);
        }); 
      },
      save_access_token_details: function (req, callback) { 
        var d = new Date();
        var sql = "INSERT INTO auth (device_id, customer_id, created_at, access_token, ip_address, is_active)" +
          "VALUES (:device_id, :cust_id, :created_at, :access_token, :ip_add, 1) ";
        sequelize.query(sql, {
          replacements: {
            device_id: req.device_code ,
            cust_id: req.id ,
            created_at: d,
            access_token: req.access_token,
            ip_add: req.ip_add  
          },
          raw: true
        }).spread(function (data, metadata) {
          callback(null, data);
        }).catch(function (err) {
          callback(err, null);
        });; 
      }
    },
    tableName: 'auth',
    timestamps: true,
    underscored: true
  });
  return auth;
};

在我的控制器中:

var models = require('../models/auth.js'); // the above model is saved in file auth.js

models.auth.verify_user(access_token, function (err, data) {
        if (err) {
          res.status(401).send({
            'err': 'Unauthorized!'
          });
        }
        if (data) {
          models.revoke_access_token(user, function (err, data) {
            if (err) {
              res.status(401).send({
                'err': 'Unauthorized!'
              });
            }
          });
        }
        models.save_access_token_details(payload, function (err, data) {
          if (err) {
            res.status(401).send({
              'err': 'Unauthorized!'
            });
          } else {
            console.log(err, data);
            res.send(data);
          }
        });
      });

但每次都存在错误::

  

TypeError:无法调用方法' verify_user'未定义的       在SignStream。 (/home/salim/Documents/proj/platform/oAuth/controllers/validate.js:25:19)       at SignStream.EventEmitter.emit(events.js:95:17)       at SignStream.sign(/home/salim/Documents/proj/platform/oAuth/node_modules/jsonwebtoken/node_modules/jws/lib/sign-stream.js:54:8)       在SignStream。 (/home/salim/Documents/proj/platform/oAuth/node_modules/jsonwebtoken/node_modules/jws/lib/sign-stream.js:37:12)       在DataStream.g(events.js:180:16)       在DataStream.EventEmitter.emit(events.js:92:17)       在DataStream。 (/home/salim/Documents/proj/platform/oAuth/node_modules/jsonwebtoken/node_modules/jws/lib/data-stream.js:20:12)       at process._tickCallback(node.js:415:13)   stream.js:94         扔掉//管道中未处理的流错误。 ^   错误:读取ECONNRESET       在errnoException(net.js:901:11)       在Pipe.onread(net.js:556:19)

请帮助我哪里出错?为什么orm无法识别功能????

1 个答案:

答案 0 :(得分:0)

初始化models.auth后,您的问题是undefinedmodels。由于models.authundefined,因此您无法调用其功能,也无法使用其成员。

authmodule.exports内的局部变量。即使你退回它,在它的范围之外你也不能使用它。

如果require拨打module.exports,那么您的modelsauth的对象完全相同,因为您返回auth,因此models.verify_user在您的代码中存在。但是,我提出以下修复:

var models = {}; //creating an empty object which will hold the models
models.auth = require('../models/auth.js'); // the above model is saved in file auth.js

然后您就可以使用models.auth