2017-02-12 62 views
1

是否有可能在Sequelize中創建自定義create方法。我希望它能傳遞一個URL來下載縮略圖照片,然後用這些數據調用一個方法來下載照片,上傳到S3,並將該S3 URL保存爲thumbnailPhotoURL。Sequelize - 自定義創建方法

下面是語法,我試圖做的一個例子:

var Sequelize = require('sequelize'); 
var sequelize = new Sequelize('database', 'username', 'password'); 

var User = sequelize.define('user', { 
    username: Sequelize.STRING, 
    birthday: Sequelize.DATE, 
    thumbnailPhotoURL: Sequelize.STRING 
}); 

sequelize.sync().then(function() { 
    return User.create({ 
    username: 'janedoe', 
    birthday: new Date(1980, 6, 20), 
    // this will be used to download and upload the thumbnailPhoto to S3 
    urlToDownloadThumbnailPhotoFrom: 'http://example.com/test.png' 
    }); 
}).then(function(jane) { 
    console.log(jane.get({ 
    plain: true 
    })); 
}); 

通知我如何我打電話User.createurlToDownloadThumbnailPhotoFrom參數,而不是thumbnailPhotoURL參數

回答

2

您可以使用前創建鉤子無需定義自定義創建功能

var Sequelize = require('sequelize'); 
var sequelize = new Sequelize('database', 'username', 'password'); 

var User = sequelize.define('user', { 
    username: Sequelize.STRING, 
    birthday: Sequelize.DATE, 
    thumbnailPhotoURL: Sequelize.STRING 
}); 


User.beforeCreate(function(model, options, cb) { 
    var urlToDownloadThumbnailPhotoFrom = model.urlToDownloadThumbnailPhotoFrom; 


//.....Here you write the logic to get s3 url using urlToDownloadThumbnailPhotoFrom and then assign it to model and call the call back it will automatically get saved 

    model.thumbnailPhotoURL = thumbnailPhotoURL; 
    cb(); 
});