Sequelize - 自定义创建方法
问题描述:
是否有可能在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.create
与urlToDownloadThumbnailPhotoFrom
参数,而不是thumbnailPhotoURL
参数
答
您可以使用前创建钩子无需定义自定义创建功能
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();
});