1 import * as Sequelize from 'sequelize'
3 import { isUserUsernameValid } from '../../helpers'
5 import { addMethodsToModel } from '../utils'
11 } from './author-interface'
13 let Author: Sequelize.Model<AuthorInstance, AuthorAttributes>
14 let findOrCreateAuthor: AuthorMethods.FindOrCreateAuthor
16 export default function defineAuthor (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
17 Author = sequelize.define<AuthorInstance, AuthorAttributes>('Author',
20 type: DataTypes.STRING,
23 usernameValid: value => {
24 const res = isUserUsernameValid(value)
25 if (res === false) throw new Error('Username is not valid.')
43 fields: [ 'name', 'podId' ],
50 const classMethods = [ associate, findOrCreateAuthor ]
51 addMethodsToModel(Author, classMethods)
56 // ---------------------------------------------------------------------------
58 function associate (models) {
59 Author.belongsTo(models.Pod, {
67 Author.belongsTo(models.User, {
75 Author.hasMany(models.Video, {
84 findOrCreateAuthor = function (name: string, podId: number, userId: number, transaction: Sequelize.Transaction) {
91 const query: Sequelize.FindOrInitializeOptions<AuthorAttributes> = {
97 return Author.findOrCreate(query).then(([ authorInstance ]) => authorInstance)