Browse Source

Database package: Add database service

dev
David Ludwig 4 years ago
parent
commit
f03faf95a8
3 changed files with 61 additions and 27 deletions
  1. +1
    -0
      packages/database/package.json
  2. +59
    -0
      packages/database/src/DatabaseService.ts
  3. +1
    -27
      packages/database/src/index.ts

+ 1
- 0
packages/database/package.json View File

@ -9,6 +9,7 @@
"clean": "rimraf ./dist"
},
"dependencies": {
"@autoplex/microservice": "^0.0.0",
"@autoplex/utils": "^0.0.0",
"bcrypt": "^5.0.1",
"mysql": "^2.18.1",


+ 59
- 0
packages/database/src/DatabaseService.ts View File

@ -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)
});
}
}

+ 1
- 27
packages/database/src/index.ts View File

@ -1,28 +1,2 @@
import * as entities from "./entities";
import { createConnection } from "typeorm";
/**
* Export the entities
*/
export * from "./entities";
/**
* A convenience function to connect to the database
*/
export default async function 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),
migrations : ["src/migrations/*.ts"]
});
}
export * from "./DatabaseService";

Loading…
Cancel
Save