1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2024-11-03 21:04:03 +08:00
pigallery2/backend/model/mysql/MySQLConnection.ts

76 lines
2.4 KiB
TypeScript
Raw Normal View History

2016-12-27 23:09:47 +08:00
import "reflect-metadata";
2017-06-04 21:25:08 +08:00
import {Connection, createConnection} from "typeorm";
2016-12-27 23:09:47 +08:00
import {UserEntity} from "./enitites/UserEntity";
import {UserRoles} from "../../../common/entities/UserDTO";
2016-12-28 03:55:51 +08:00
import {PhotoEntity, PhotoMetadataEntity} from "./enitites/PhotoEntity";
import {DirectoryEntity} from "./enitites/DirectoryEntity";
2017-06-04 21:25:08 +08:00
import {Config} from "../../../common/config/private/Config";
2016-12-27 23:09:47 +08:00
export class MySQLConnection {
constructor() {
}
private static connection: Connection = null;
public static getConnection(): Promise<Connection> {
return new Promise<Connection>((resolve, reject) => {
if (this.connection != null) {
return resolve(this.connection);
}
createConnection({
driver: {
type: "mysql",
host: Config.Server.database.mysql.host,
port: 3306,
username: Config.Server.database.mysql.username,
password: Config.Server.database.mysql.password,
database: Config.Server.database.mysql.database
},
entities: [
2016-12-28 03:55:51 +08:00
UserEntity,
DirectoryEntity,
2016-12-28 03:55:51 +08:00
PhotoMetadataEntity,
PhotoEntity
2016-12-27 23:09:47 +08:00
],
autoSchemaSync: true,
2016-12-28 03:55:51 +08:00
logging: {
logQueries: true,
logOnlyFailedQueries: true,
logFailedQueryError: true,
logSchemaCreation: true
}
2016-12-27 23:09:47 +08:00
}).then((conn) => {
this.connection = conn;
return resolve(this.connection);
}).catch(err => reject(err));
});
}
public static init(): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.getConnection().then(async connection => {
let userRepository = connection.getRepository(UserEntity);
let admins = await userRepository.find({role: UserRoles.Admin});
if (admins.length == 0) {
let a = new UserEntity();
a.name = "admin";
a.password = "admin";
a.role = UserRoles.Admin;
await userRepository.persist(a);
}
resolve();
}).catch(err => reject(err));
});
}
}