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