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