This repository has been archived on 2026-05-05. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
Web-Dev-Old/nodeJS/Learning/06/src/index.ts
2024-12-30 04:14:32 +00:00

103 lines
2.6 KiB
TypeScript

import dotenv from "dotenv";
dotenv.config({ path: ".env" });
import express, { Application, Request, Response } from "express";
import pg from "./database/pg";
import { PoolClient } from "pg";
const app: Application = express();
const port: number = parseInt(process.env.PORT as string) || 3000;
//Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
//Setting up for EJS
app.set("views", `./src/views`);
app.set("view engine", "ejs");
//Static route
app.use(express.static(`${__dirname}/../public`));
//check and send index ejs
app.get("/", (_req: Request, res: Response): void => {
let todos: string[] = [];
//Query postgres database to get all todos (async await)
pg.query("SELECT * FROM todos", async (err: Error, result: any) => {
if (err) {
console.log("Error querying todos", err);
return;
}
todos = result.rows.map((row: any) => row.todo);
}
res.render("index",{
todos,
});
});
app.post("/form-action", (req: Request, res: Response): void => {
const todo: string = req.body.todo;
//query postgres to insert todo, $1 is a placeholder for the value of todo
pg.query("INSERT INTO todos (todo) VALUES ($1)", [todo], (err: Error) => {
if (err) {
console.log("Error inserting todo", err);
return;
}
console.log(`Inserted ${todo} successfully`);
});
res.redirect("/");
});
// app.delete("/delete-todo/:todo", (req: Request, res: Response): void => {
// //delete todo from postgres
// });
app.listen(port, (): void => {
console.log(`Server is running on port ${port}`);
});
//Connect to postgres, postgres initialization
pg.connect(
(err: Error | undefined, client: PoolClient | undefined, done): void => {
if (err) {
console.log("Error connecting to pg", err);
return;
}
if (!client) {
console.log("No client found");
return;
}
// Attempt to Query (asking the database, to check it is connected), it might take us a while and we wont be able to run the rest of the program
// Async this
client.query("SELECT NOW()", async (err: Error, _result: any) => {
if (err) {
console.log("Error querying pg", err);
return;
}
//Create the table if no error (await)
//Query statement, instruction "CREATE TABLE IF NOT EXISTS todos", there is a whole table, https://www.w3schools.com/sql/default.asp
//VACHAR is a string, 255 is the max length of the string
await client.query(
`CREATE TABLE IF NOT EXISTS todos (
todo VARCHAR(255) NOT NULL
)`,
(err: Error) => {
console.log("Error creating table", err);
return;
}
);
console.log("Connected to postgres successfully");
done();
});
}
);