1 import * as Sequelize from 'sequelize'
3 import { isUserUsernameValid } from '../helpers'
5 import { addMethodsToModel } from './utils'
12 } from './author-interface'
14 let Author: Sequelize.Model<AuthorInstance, AuthorAttributes>
15 let findOrCreateAuthor: AuthorMethods.FindOrCreateAuthor
17 export default function defineAuthor (sequelize: Sequelize.Sequelize, DataTypes) {
18 Author = sequelize.define<AuthorInstance, AuthorAttributes>('Author',
21 type: DataTypes.STRING,
24 usernameValid: function (value) {
25 const res = isUserUsernameValid(value)
26 if (res === false) throw new Error('Username is not valid.')
44 fields: [ 'name', 'podId' ],
51 const classMethods = [ associate, findOrCreateAuthor ]
52 addMethodsToModel(Author, classMethods)
57 // ---------------------------------------------------------------------------
59 function associate (models) {
60 Author.belongsTo(models.Pod, {
68 Author.belongsTo(models.User, {
77 findOrCreateAuthor = function (
81 transaction: Sequelize.Transaction,
82 callback: AuthorMethods.FindOrCreateAuthorCallback
95 if (transaction !== null) query.transaction = transaction
97 Author.findOrCreate(query).asCallback(function (err, result) {
98 if (err) return callback(err)
100 // [ instance, wasCreated ]
101 return callback(null, result[0])