]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/initializers/database.ts
Display error message in signup page (#128)
[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 export type PeerTubeDatabase = {
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 database: PeerTubeDatabase = {}
59
60 const sequelize = new Sequelize(dbname, username, password, {
61 dialect: 'postgres',
62 host: CONFIG.DATABASE.HOSTNAME,
63 port: CONFIG.DATABASE.PORT,
64 benchmark: isTestInstance(),
65 isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE,
66 operatorsAliases: false,
67
68 logging: (message: string, benchmark: number) => {
69 let newMessage = message
70 if (isTestInstance() === true && benchmark !== undefined) {
71 newMessage += ' | ' + benchmark + 'ms'
72 }
73
74 logger.debug(newMessage)
75 }
76 })
77
78 database.sequelize = sequelize
79
80 database.init = async (silent: boolean) => {
81 const modelDirectory = join(__dirname, '..', 'models')
82
83 const filePaths = await getModelFiles(modelDirectory)
84
85 for (const filePath of filePaths) {
86 try {
87 const model = sequelize.import(filePath)
88
89 database[model['name']] = model
90 } catch (err) {
91 logger.error('Cannot import database model %s.', filePath, err)
92 process.exit(0)
93 }
94 }
95
96 for (const modelName of Object.keys(database)) {
97 if ('associate' in database[modelName]) {
98 try {
99 database[modelName].associate(database)
100 } catch (err) {
101 logger.error('Cannot associate model %s.', modelName, err)
102 process.exit(0)
103 }
104 }
105 }
106
107 if (!silent) logger.info('Database %s is ready.', dbname)
108
109 return
110 }
111
112 // ---------------------------------------------------------------------------
113
114 export {
115 database
116 }
117
118 // ---------------------------------------------------------------------------
119
120 async 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 })
132
133 const tasks: Promise<any>[] = []
134
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)
138
139 const promise = readdirPromise(modelDirectoryPath)
140 .then(files => {
141 const filteredFiles = files
142 .filter(file => {
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
151 })
152 .map(file => join(modelDirectoryPath, file))
153
154 return filteredFiles
155 })
156
157 tasks.push(promise)
158 }
159
160 const filteredFilesArray: string[][] = await Promise.all(tasks)
161 return flattenDepth<string>(filteredFilesArray, 1)
162 }