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