/
index.ts
56 lines (49 loc) · 1.66 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import "dotenv/config";
import "reflect-metadata";
import { Event } from "./entities/Event";
import { DataSource } from "typeorm";
import express, { Express, Request, Response, json } from "express";
const app: Express = express();
const port: number = 3000;
app.use(json());
const AppDataSource = new DataSource({
type: "postgres",
host: process.env.db_host,
port: process.env.db_port as unknown as number,
username: process.env.db_user,
password: process.env.db_password,
database: process.env.db_name,
entities: [Event],
synchronize: true,
logging: false,
});
const eventRepository = AppDataSource.getRepository(Event);
// GET All Events.
app.get("/api/v1/events", async (req: Request, res: Response) => {
const allEvents = await eventRepository.find();
return res.status(200).json(allEvents);
});
// GET One Event By ID.
app.get("/api/v1/events/:id", async (req: Request, res: Response) => {
const eventId: number = parseInt(req.params.id);
const foundEvent = await eventRepository.findOneBy({
id: eventId,
});
return res.status(201).json(foundEvent);
});
// POST new event.
app.post("/api/v1/events", async (req: Request, res: Response) => {
const eventName: string = req.body.name;
const newEvent: Event = new Event(eventName);
await eventRepository.save(newEvent);
const allEevents = await AppDataSource.manager.find(Event);
return res.status(201).json(allEevents);
});
AppDataSource.initialize()
.then(() => {
console.log("Database connection successful ! Yeah baby !");
app.listen(port, () => {
console.log(`Server successfully listening on port ${port} ! Oh yeah !`);
});
})
.catch((error) => console.log(error));