-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
60 lines (52 loc) · 1.53 KB
/
index.js
File metadata and controls
60 lines (52 loc) · 1.53 KB
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
require("dotenv").config();
const express = require("express");
const app = express();
const pgp = require("pg-promise")();
const bodyParser = require("body-parser");
const cors = require("cors");
const PORT = process.env.PORT || 8080;
app.use(cors()); // using cors to allow cross origin requests
app.use(bodyParser.json()); // body parser to parse request body
// database config / connection
const dbConfig = {
host: "db",
port: 5432,
database: process.env.POSTGRES_DB,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
};
const db = pgp(dbConfig);
/***** Defining endpoints *****/
app.get("/fetch-users", (req, res) => {
db.any("SELECT username, profile_image, description FROM users;")
.then((data) => {
res.json(data);
})
.catch((err) => {
res.json(err);
});
});
app.post("/add-user", (req, res) => {
const { username, profile_image, description } = req.body || {};
if (!username || !profile_image || !description) {
res.status(400).json({ message: "Please provide all fields" });
} else {
db.query(
"INSERT INTO users (username, profile_image, description) VALUES ($1, $2, $3) returning username, description, profile_image;",
[username, profile_image, description]
)
.then((data) => {
console.log(data[0]);
res.json(data[0]);
})
.catch((err) => {
res.json(err);
});
}
});
app.get("/", (req, res) => {
res.send("hello world");
});
app.listen(PORT, () => {
console.log(`Server initiated on ${PORT}`);
});