]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/initializers/database.ts
Fix test
[github/Chocobozzz/PeerTube.git] / server / initializers / database.ts
CommitLineData
65fcc311 1import { join } from 'path'
6fcd19ba 2import { flattenDepth } from 'lodash'
b0f9f39e 3require('pg').defaults.parseInt8 = true // Avoid BIGINT to be converted to string
4d4e5cd4 4import * as Sequelize from 'sequelize'
2295ce6c 5import { AvatarModel } from '../models/avatar'
8c308c2b 6
65fcc311
C
7import { CONFIG } from './constants'
8// Do not use barrel, we need to load database first
9import { logger } from '../helpers/logger'
6fcd19ba 10import { isTestInstance, readdirPromise } from '../helpers/core-utils'
fdbda9e3
C
11
12import { VideoModel } from './../models/video/video-interface'
13import { VideoTagModel } from './../models/video/video-tag-interface'
14import { BlacklistedVideoModel } from './../models/video/video-blacklist-interface'
15import { VideoFileModel } from './../models/video/video-file-interface'
16import { VideoAbuseModel } from './../models/video/video-abuse-interface'
72c7248b 17import { VideoChannelModel } from './../models/video/video-channel-interface'
e4f97bab
C
18import { UserModel } from '../models/account/user-interface'
19import { AccountVideoRateModel } from '../models/account/account-video-rate-interface'
20import { AccountFollowModel } from '../models/account/account-follow-interface'
fdbda9e3 21import { TagModel } from './../models/video/tag-interface'
60862425 22import { ServerModel } from '../models/server/server-interface'
fdbda9e3
C
23import { OAuthTokenModel } from './../models/oauth/oauth-token-interface'
24import { OAuthClientModel } from './../models/oauth/oauth-client-interface'
25import { JobModel } from './../models/job/job-interface'
e4f97bab 26import { AccountModel } from './../models/account/account-interface'
fdbda9e3 27import { ApplicationModel } from './../models/application/application-interface'
d8465018
C
28import { VideoChannelShareModel } from '../models/video/video-channel-share-interface'
29import { VideoShareModel } from '../models/video/video-share-interface'
8c308c2b 30
65fcc311
C
31const dbname = CONFIG.DATABASE.DBNAME
32const username = CONFIG.DATABASE.USERNAME
33const password = CONFIG.DATABASE.PASSWORD
8c308c2b 34
74bb2cb8 35export type PeerTubeDatabase = {
e02643f3 36 sequelize?: Sequelize.Sequelize,
6fcd19ba 37 init?: (silent: boolean) => Promise<void>,
e02643f3
C
38
39 Application?: ApplicationModel,
2295ce6c 40 Avatar?: AvatarModel,
e4f97bab 41 Account?: AccountModel,
e02643f3
C
42 Job?: JobModel,
43 OAuthClient?: OAuthClientModel,
44 OAuthToken?: OAuthTokenModel,
60862425 45 Server?: ServerModel,
e02643f3 46 Tag?: TagModel,
e4f97bab
C
47 AccountVideoRate?: AccountVideoRateModel,
48 AccountFollow?: AccountFollowModel,
e02643f3
C
49 User?: UserModel,
50 VideoAbuse?: VideoAbuseModel,
72c7248b 51 VideoChannel?: VideoChannelModel,
d8465018
C
52 VideoChannelShare?: VideoChannelShareModel,
53 VideoShare?: VideoShareModel,
93e1258c 54 VideoFile?: VideoFileModel,
e02643f3
C
55 BlacklistedVideo?: BlacklistedVideoModel,
56 VideoTag?: VideoTagModel,
57 Video?: VideoModel
74bb2cb8
C
58}
59
60const database: PeerTubeDatabase = {}
b769007f
C
61
62const sequelize = new Sequelize(dbname, username, password, {
feb4bdfd 63 dialect: 'postgres',
65fcc311
C
64 host: CONFIG.DATABASE.HOSTNAME,
65 port: CONFIG.DATABASE.PORT,
66 benchmark: isTestInstance(),
eb080476 67 isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE,
c2962505 68 operatorsAliases: false,
7920c273 69
075f16ca 70 logging: (message: string, benchmark: number) => {
165cdc75
C
71 if (process.env.NODE_DB_LOG === 'false') return
72
7920c273 73 let newMessage = message
769d3321 74 if (isTestInstance() === true && benchmark !== undefined) {
7920c273
C
75 newMessage += ' | ' + benchmark + 'ms'
76 }
77
78 logger.debug(newMessage)
79 }
feb4bdfd
C
80})
81
b769007f 82database.sequelize = sequelize
feb4bdfd 83
f5028693 84database.init = async (silent: boolean) => {
65fcc311 85 const modelDirectory = join(__dirname, '..', 'models')
c45f7f84 86
f5028693 87 const filePaths = await getModelFiles(modelDirectory)
b769007f 88
f5028693 89 for (const filePath of filePaths) {
9567011b
C
90 try {
91 const model = sequelize.import(filePath)
b769007f 92
9567011b
C
93 database[model['name']] = model
94 } catch (err) {
95 logger.error('Cannot import database model %s.', filePath, err)
96 process.exit(0)
97 }
f5028693 98 }
b769007f 99
f5028693
C
100 for (const modelName of Object.keys(database)) {
101 if ('associate' in database[modelName]) {
59c857da
C
102 try {
103 database[modelName].associate(database)
104 } catch (err) {
105 logger.error('Cannot associate model %s.', modelName, err)
106 process.exit(0)
107 }
f5028693
C
108 }
109 }
b769007f 110
f5028693
C
111 if (!silent) logger.info('Database %s is ready.', dbname)
112
d412e80e 113 return
b769007f 114}
65fcc311
C
115
116// ---------------------------------------------------------------------------
117
e02643f3
C
118export {
119 database
120}
74889a71
C
121
122// ---------------------------------------------------------------------------
123
f5028693
C
124async function getModelFiles (modelDirectory: string) {
125 const files = await readdirPromise(modelDirectory)
126 const directories = files.filter(directory => {
127 // Find directories
128 if (
129 directory.endsWith('.js.map') ||
130 directory === 'index.js' || directory === 'index.ts' ||
131 directory === 'utils.js' || directory === 'utils.ts'
132 ) return false
133
134 return true
135 })
74889a71 136
e4f97bab 137 const tasks: Promise<any>[] = []
6fcd19ba 138
f5028693
C
139 // For each directory we read it and append model in the modelFilePaths array
140 for (const directory of directories) {
141 const modelDirectoryPath = join(modelDirectory, directory)
6fcd19ba 142
f5028693
C
143 const promise = readdirPromise(modelDirectoryPath)
144 .then(files => {
145 const filteredFiles = files
146 .filter(file => {
6fcd19ba
C
147 if (
148 file === 'index.js' || file === 'index.ts' ||
149 file === 'utils.js' || file === 'utils.ts' ||
150 file.endsWith('-interface.js') || file.endsWith('-interface.ts') ||
151 file.endsWith('.js.map')
152 ) return false
153
154 return true
f5028693
C
155 })
156 .map(file => join(modelDirectoryPath, file))
74889a71 157
f5028693 158 return filteredFiles
74889a71 159 })
6fcd19ba 160
f5028693
C
161 tasks.push(promise)
162 }
163
164 const filteredFilesArray: string[][] = await Promise.all(tasks)
165 return flattenDepth<string>(filteredFilesArray, 1)
74889a71 166}