2017-02-12 8 views
1

にカスタム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 
    })); 
}); 

私はurlToDownloadThumbnailPhotoFromパラメータでUser.createを呼んでいるかに注意してくださいではなく、あなたが前に使用することができます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(); 
}); 
関連する問題