2017-04-05 77 views
0

我想用一個銀行賬戶使用sequelize和nodejs建立一個存款和提款的簡單API,但我有點困惑,我如何使用我的方法,我把它放在classmethods。任何人都可以請展示我如何使用這個到我的控制器。下面是我的模型Sequelize ClassMethods

'use strict'; 
    module.exports = function(sequelize, DataTypes) { 
    var Account = sequelize.define('Account', { 
     name: DataTypes.STRING, 
     balance: DataTypes.DOUBLE, 
     pin: DataTypes.INTEGER, 

    }, { 
     classMethods: { 
     associate: function(models) { 
     // associations can be defined here 
    }, 

    addMoney: function(amount){ 

     amount = Math.abs(amount); 

     return this.increment('balance', {by : amount}).save(); 


    }, 

    withdrawMoney: function(amount){ 

      amount = Math.abs(amount); 

     return this.decrement('balance', {by : amount}).save(); 

     } 


     } 



     }); 
     return Account; 
     } 

下面是我的控制器,但我不知道如何使用我的類方法中的控制器

 var models = require('../models/index'); 

    module.exports = { 

    newAccount(req, res, next){ 

     models.Account.create({ 
      balance: req.body.balance, 
      note: req.body.note, 
      pin: req.body.pin, 





     }).then(function(account){ 

      res.json(account); 

     }).catch(function(error){ 

      res.json(error) 
     }) 
}, 

    listAccount(req, res, next){ 

    models.Account. 
       findAll({ 

       }) 
       .then(function(accounts) { 
         res.status(200).send(accounts); 
        }).catch(function(error){ 

         res.status(400).send(error) 
        }); 

     } 
    } 

,這是我的情況下,路線,這只是路線避免張貼太多的代碼

app.get('/accounts', accountCtrl.listAccount); 
app.post('/account/new', accountCtrl.newAccount); 
app.put('/account/:id', accountCtrl.updateAccount); 
app.delete('/account/:id', accountCtrl.removeAccount); 

感謝您在avdance任何幫助,我是新來sequelize

回答

1

您正在考慮實例方法。實例方法中的this將是一個帳戶。

With classMethodsthis是它自己的類。當需要定義關於許多實例的自定義功能時,類方法很有用。

在您的例子,也許你想運行一個函數每月一次充電儲蓄賬戶低於一定數額的費用(的東西,我的銀行呢!)

classMethods: { 
    async findAndCharge(n) { 
    const accounts = await this.findAll({ where: { balance: { $lte: n } } }); 

    for (const account of accounts) { 
     await account.charge() 
    } 
    } 
} 

這是一個有些人爲的例子,但正如您可以看到,類方法中的thisAccount(帶有上限)而不是account小寫字母。

在其他情況下,這有時是一種靜態方法。

在你的情況你應該切換到instanceMethods