-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
67 lines (61 loc) · 1.71 KB
/
app.js
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
57
58
59
60
61
62
63
64
65
66
67
require("dotenv").config();
const express = require("express");
const { Client } = require("pg");
const Url = require("./models/urlModel");
const app = express();
const client = new Client(process.env.DATABASE_URL);
const connectDB = async () => {
try {
await client.connect();
console.log("PostgresDb connected.");
} catch (err) {
console.log("error postgresdB:", err);
process.exit(1);
}
};
connectDB();
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(__dirname + "/public"));
app.listen(process.env.PORT || 3000, () => {
console.log(`App running on port ${process.env.PORT}...`);
});
app.get("/", async (req, res) => {
try {
const urls = await Url.getAllUrls();
res.render("index", { urls: urls.rows });
} catch (error) {
console.log("failed to get all urls. Error:", error);
res.status(500).send(`${error}`);
}
});
app.post("/shorten", async (req, res) => {
try {
await Url.createUrl(req.body.fullUrl);
res.redirect("/");
} catch (error) {
console.log("failed to get all urls. Error:", error);
res.status(500).send(`${error}`);
}
});
app.post("/delete", async (req, res) => {
try {
await Url.deleteUrl(req.body.shortUrl);
res.redirect("/");
} catch (error) {
console.log("failed to get all urls. Error:", error);
res.status(500).send(`${error}`);
}
});
app.post("/:shortUrl", async (req, res) => {
try {
await Url.incrementClickCount(req.body.shortUrl);
res.redirect("/");
} catch (error) {
console.log("failed to get all urls. Error:", error);
res.status(500).send(`${error}`);
}
});
module.exports = app;