|
|
@ -0,0 +1,59 @@ |
|
|
|
import { InternalService } from "@autoplex/microservice"; |
|
|
|
import { env, secret } from "@autoplex/utils"; |
|
|
|
import { createConnection, Connection } from "typeorm"; |
|
|
|
import * as entities from "./entities"; |
|
|
|
|
|
|
|
/** |
|
|
|
* A convenience database service |
|
|
|
*/ |
|
|
|
export class Database extends InternalService |
|
|
|
{ |
|
|
|
/** |
|
|
|
* The active database connection |
|
|
|
*/ |
|
|
|
protected connection!: Connection; |
|
|
|
|
|
|
|
/** |
|
|
|
* The name of the service |
|
|
|
*/ |
|
|
|
public readonly NAME = "Database"; |
|
|
|
|
|
|
|
/** |
|
|
|
* Boot the database service |
|
|
|
*/ |
|
|
|
public async boot() { |
|
|
|
let host = env("DB_HOST"); |
|
|
|
let port = parseInt(env("DB_PORT")); |
|
|
|
let username = env("DB_USER"); |
|
|
|
let password = await secret(env("DB_PASSWORD_FILE")); |
|
|
|
let database = env("DB_DATABASE"); |
|
|
|
this.connection = await this.connectToDatabase(host, port, username, password, database); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* Shutdown the database service |
|
|
|
*/ |
|
|
|
public async shutdown() { |
|
|
|
await this.connection.close(); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* A convenience function to connect to the database |
|
|
|
*/ |
|
|
|
private async connectToDatabase(host: string, port: number, username: string, password: string, |
|
|
|
database: string) |
|
|
|
{ |
|
|
|
// Create the database connection
|
|
|
|
return await createConnection({ |
|
|
|
type : "mysql", |
|
|
|
host : host, |
|
|
|
port : port, |
|
|
|
username : username, |
|
|
|
password : password, |
|
|
|
database : database, |
|
|
|
// synchronize: process.env["NODE_ENV"] != "production",
|
|
|
|
synchronize: true, // Seems stable enough for my liking
|
|
|
|
entities : Object.values(entities) |
|
|
|
}); |
|
|
|
} |
|
|
|
} |