From 65fcc3119c334b75dd13bcfdebf186afdc580a8f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Mon, 15 May 2017 22:22:03 +0200 Subject: First typescript iteration --- server/models/author.ts | 90 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 server/models/author.ts (limited to 'server/models/author.ts') diff --git a/server/models/author.ts b/server/models/author.ts new file mode 100644 index 000000000..4a7396929 --- /dev/null +++ b/server/models/author.ts @@ -0,0 +1,90 @@ +import { isUserUsernameValid } from '../helpers' + +module.exports = function (sequelize, DataTypes) { + const Author = sequelize.define('Author', + { + name: { + type: DataTypes.STRING, + allowNull: false, + validate: { + usernameValid: function (value) { + const res = isUserUsernameValid(value) + if (res === false) throw new Error('Username is not valid.') + } + } + } + }, + { + indexes: [ + { + fields: [ 'name' ] + }, + { + fields: [ 'podId' ] + }, + { + fields: [ 'userId' ], + unique: true + }, + { + fields: [ 'name', 'podId' ], + unique: true + } + ], + classMethods: { + associate, + + findOrCreateAuthor + } + } + ) + + return Author +} + +// --------------------------------------------------------------------------- + +function associate (models) { + this.belongsTo(models.Pod, { + foreignKey: { + name: 'podId', + allowNull: true + }, + onDelete: 'cascade' + }) + + this.belongsTo(models.User, { + foreignKey: { + name: 'userId', + allowNull: true + }, + onDelete: 'cascade' + }) +} + +function findOrCreateAuthor (name, podId, userId, transaction, callback) { + if (!callback) { + callback = transaction + transaction = null + } + + const author = { + name, + podId, + userId + } + + const query: any = { + where: author, + defaults: author + } + + if (transaction) query.transaction = transaction + + this.findOrCreate(query).asCallback(function (err, result) { + if (err) return callback(err) + + // [ instance, wasCreated ] + return callback(null, result[0]) + }) +} -- cgit v1.2.3