Skip to content
Snippets Groups Projects
Commit 81625882 authored by alrwasheda's avatar alrwasheda :speech_balloon:
Browse files

Forcing any new (given) DB. Create tables. Show tables in DB.

parent 8c1aa256
No related branches found
No related tags found
No related merge requests found
...@@ -2,15 +2,18 @@ import Customer from "./models/Customer"; ...@@ -2,15 +2,18 @@ import Customer from "./models/Customer";
import Boat from "./models/Boat"; import Boat from "./models/Boat";
import Worker from "./models/Worker"; import Worker from "./models/Worker";
import CheckIn from "./models/CheckIn"; import CheckIn from "./models/CheckIn";
import { checkDB } from "./seqConnection";
const isDev = process.env.NODE_ENV === "development"; const isDev = process.env.NODE_ENV === "development";
const dbInit = () => const dbInit = async () => {
Promise.all([ await Customer.sync({ alter: isDev });
Customer.sync({ alter: isDev }), await Boat.sync({ alter: isDev });
Boat.sync({ alter: isDev }), await Worker.sync({ alter: isDev });
Worker.sync({ alter: isDev }), await CheckIn.sync({ alter: isDev });
CheckIn.sync({ alter: isDev }), };
]); const connectAndInit = async () => {
await checkDB();
export default dbInit; await dbInit();
};
export default connectAndInit;
import envVars from "./config";
import { Sequelize } from "sequelize"; import { Sequelize } from "sequelize";
import envVars from "./config";
import { Client } from "pg";
const sequelizeConnection = new Sequelize( let sequelizeConnection = new Sequelize(
envVars.dbName, envVars.dbName,
envVars.dbUser, envVars.dbUser,
envVars.dbPassword, envVars.dbPassword,
...@@ -11,12 +12,40 @@ const sequelizeConnection = new Sequelize( ...@@ -11,12 +12,40 @@ const sequelizeConnection = new Sequelize(
logging: false, logging: false,
} }
); );
export const testConnection = async () => { //check if DB in env exists. If not, create a one
try { export const checkDB = async () => {
await sequelizeConnection.authenticate(); const client = new Client({
console.log("Connection has been established successfully."); host: envVars.dbHost,
} catch (error) { port: 5432, //envVars.dbPort does not exist!
console.error("Unable to connect to the database:", error); user: envVars.dbUser,
} password: envVars.dbPassword,
});
await client.connect();
//search for db in pg-catalog. if not found, create a one
await client
.query(`SELECT * FROM pg_database WHERE datname = '${envVars.dbName}'`)
.then((res) => {
//------------------------------------------------then
if (res.rows.length === 0) {
//given db not found
console.log(
`${envVars.dbName} not found!\n${envVars.dbName} created..!`
);
client.query(`CREATE DATABASE "${envVars.dbName}"`);
sequelizeConnection = new Sequelize(
envVars.dbName,
envVars.dbUser,
envVars.dbPassword,
{
host: envVars.dbHost,
dialect: envVars.dbDriver,
logging: false,
}
);
} else {
console.log("-------\nres:\n", res.rows);
}
});
}; };
export default sequelizeConnection; export default sequelizeConnection;
import sequelizeConnection from "./seqConnection";
import { QueryTypes } from "sequelize";
import envVars from "./config";
const showTables = async () => {
//list all tables of the actual database
sequelizeConnection
.query(
`SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='${envVars.dbName}' AND TABLE_SCHEMA='public';`,
{ type: QueryTypes.SELECT }
)
.then((res) => {
//------------------------------------------------then
console.log(`TABELS IN ${envVars.dbName}\n-------------\n`, res);
});
};
export default showTables;
import "dotenv/config"; import "dotenv/config";
import express from "express"; import express from "express";
import dbInit from "./db/db_init"; import connectAndInit from "./db/db_init";
import { testConnection } from "./db/seqConnection"; import showTables from "./db/showDBTables";
//import apiRouter from "./routes";
let init = async () => { let init = async () => {
testConnection(); await connectAndInit();
await dbInit(); await showTables();
const app = express(); const app = express();
app.use(express.json()); app.use(express.json());
//app.use(apiRouter);
const port = process.env.PORT || 4000; const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server listening on port: ${port}`)); app.listen(port, () => console.log(`Server listening on port: ${port}`));
app.get("/", (req, res) => res.send("hello in server")); app.get("/", (req, res) => res.send("hello in server"));
......
  • alrwasheda :speech_balloon: @alrwasheda ·
    Author Maintainer
    • Database will be forced if not exists.
    • Tables will be created into any new (given) Database.
    • Problem of some tables being created before others, solved.
    • Testing Sequelize-Connection deleted.

    Could need installation of "pg".

    To test it:

    • change the name in .env to "Fahrtenbuch" (or any other name) and run normally using docker.
    Edited by alrwasheda
  • alrwasheda :speech_balloon: @alrwasheda ·
    Author Maintainer

    By getting this error: "src/db/seqConnection.ts(28,12): error TS7006: Parameter 'res' implicitly has an 'any' type.\n" set the value of "noImplicitAny": true in tsconfig.json to false

  • fu1106jv @fu1106jv ·
    Maintainer

    this is not an error - you can't have function arguments without a type with this setting(and it should be true in the tsconfig)

  • leandet98 @leandet98 ·
    Maintainer

    you can annotate the res as res: QueryResult

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment