From 4ff0d86208dafbdd07beb6286fd93c795db8a95f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 29 Dec 2016 18:02:03 +0100 Subject: Server: little refractoring --- server/models/author.js | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) (limited to 'server/models/author.js') diff --git a/server/models/author.js b/server/models/author.js index 5835ada99..7d15fb6ec 100644 --- a/server/models/author.js +++ b/server/models/author.js @@ -29,7 +29,9 @@ module.exports = function (sequelize, DataTypes) { } ], classMethods: { - associate + associate, + + findOrCreateAuthor } } ) @@ -56,3 +58,28 @@ function associate (models) { onDelete: 'cascade' }) } + +function findOrCreateAuthor (name, podId, userId, transaction, callback) { + if (!callback) { + callback = transaction + transaction = null + } + + const author = { + name, + podId, + userId + } + + const query = { + where: author, + defaults: author + } + + if (transaction) query.transaction = transaction + + this.findOrCreate(query).asCallback(function (err, result) { + // [ instance, wasCreated ] + return callback(err, result[0]) + }) +} -- cgit v1.2.3