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