1 import * as Sequelize from 'sequelize'
3 import { isUserUsernameValid } from '../../helpers'
4 import { removeVideoAuthorToFriends } from '../../lib'
6 import { addMethodsToModel } from '../utils'
12 } from './author-interface'
14 let Author: Sequelize.Model<AuthorInstance, AuthorAttributes>
15 let loadAuthorByPodAndUUID: AuthorMethods.LoadAuthorByPodAndUUID
16 let load: AuthorMethods.Load
17 let loadByUUID: AuthorMethods.LoadByUUID
18 let listOwned: AuthorMethods.ListOwned
19 let isOwned: AuthorMethods.IsOwned
20 let toAddRemoteJSON: AuthorMethods.ToAddRemoteJSON
22 export default function defineAuthor (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
23 Author = sequelize.define<AuthorInstance, AuthorAttributes>('Author',
27 defaultValue: DataTypes.UUIDV4,
34 type: DataTypes.STRING,
37 usernameValid: value => {
38 const res = isUserUsernameValid(value)
39 if (res === false) throw new Error('Username is not valid.')
57 fields: [ 'name', 'podId' ],
61 hooks: { afterDestroy }
65 const classMethods = [
67 loadAuthorByPodAndUUID,
72 const instanceMethods = [
76 addMethodsToModel(Author, classMethods, instanceMethods)
81 // ---------------------------------------------------------------------------
83 function associate (models) {
84 Author.belongsTo(models.Pod, {
92 Author.belongsTo(models.User, {
100 Author.hasMany(models.VideoChannel, {
110 function afterDestroy (author: AuthorInstance) {
111 if (author.isOwned()) {
112 const removeVideoAuthorToFriendsParams = {
116 return removeVideoAuthorToFriends(removeVideoAuthorToFriendsParams)
122 toAddRemoteJSON = function (this: AuthorInstance) {
131 isOwned = function (this: AuthorInstance) {
132 return this.podId === null
135 // ------------------------------ STATICS ------------------------------
137 listOwned = function () {
138 const query: Sequelize.FindOptions<AuthorAttributes> = {
144 return Author.findAll(query)
147 load = function (id: number) {
148 return Author.findById(id)
151 loadByUUID = function (uuid: string) {
152 const query: Sequelize.FindOptions<AuthorAttributes> = {
158 return Author.findOne(query)
161 loadAuthorByPodAndUUID = function (uuid: string, podId: number, transaction: Sequelize.Transaction) {
162 const query: Sequelize.FindOptions<AuthorAttributes> = {
170 return Author.find(query)