|
| 1 | +import { parseIntSafe } from "@hanabi/utils"; |
| 2 | +import { Client } from "pg"; |
| 3 | +import { logger } from "./logger"; |
| 4 | + |
| 5 | +export async function databaseInit(): Promise<void> { |
| 6 | + const client = new Client({}); |
| 7 | + await client.connect(); |
| 8 | + |
| 9 | + const res = await client.query("SELECT $1::text as message", [ |
| 10 | + "Hello world!", |
| 11 | + ]); |
| 12 | + console.log(res.rows[0].message); // Hello world! |
| 13 | + await client.end(); |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * Read the database configuration from environment variables. (They should already be loaded from |
| 18 | + * the ".env" file at this point.) |
| 19 | + */ |
| 20 | +function getDatabaseConfig() { |
| 21 | + let host = process.env["DB_HOST"]; |
| 22 | + if (host === undefined || host === "") { |
| 23 | + host = "localhost"; |
| 24 | + logger.info(`DB_HOST not specified; using a default value of: ${host}`); |
| 25 | + } |
| 26 | + |
| 27 | + const portString = process.env["DB_PORT"]; |
| 28 | + let port: number; |
| 29 | + if (portString === undefined || portString === "") { |
| 30 | + port = 5432; // The default port for PostgreSQL. |
| 31 | + logger.info(`DB_PORT not specified; using a default value of: ${port}`); |
| 32 | + } else { |
| 33 | + port = parseIntSafe(portString); |
| 34 | + if (Number.isNaN(port)) { |
| 35 | + throw new TypeError( |
| 36 | + `Failed to parse the "DB_PORT" environment variable: ${portString}`, |
| 37 | + ); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + let user = process.env["DB_USER"]; |
| 42 | + if (user === undefined || user === "") { |
| 43 | + user = "hanabiuser"; |
| 44 | + logger.info(`DB_USER not specified; using a default value of: ${user}`); |
| 45 | + } |
| 46 | + |
| 47 | + let password = process.env["DB_PASSWORD"]; |
| 48 | + if (password === undefined || password === "") { |
| 49 | + password = "1234567890"; |
| 50 | + logger.info( |
| 51 | + `DB_PASSWORD not specified; using a default value of: ${password}`, |
| 52 | + ); |
| 53 | + } |
| 54 | + |
| 55 | + /* |
| 56 | +
|
| 57 | + dbName = os.Getenv("DB_NAME") |
| 58 | + if len(dbPass) == 0 { |
| 59 | + defaultName := "hanabi" |
| 60 | + logger.Info("DB_NAME not specified; using default value of \"" + defaultName + "\".") |
| 61 | + dbName = defaultName |
| 62 | + } |
| 63 | +
|
| 64 | + */ |
| 65 | + |
| 66 | + return { |
| 67 | + host, |
| 68 | + port, |
| 69 | + }; |
| 70 | +} |
0 commit comments