-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
70 lines (56 loc) · 1.96 KB
/
server.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
68
69
70
const express = require("express")
const cors = require("cors");
const {Pool} = require('pg')
const pool = new Pool({
connectionString: "postgres://afuxtawmyieyjo:13bb8d5ece25a9242c5ca5f55001027d17f329cfd3a91cecf780c5024e0239a4@ec2-3-237-55-96.compute-1.amazonaws.com:5432/d9aqkclakvsmeg",
ssl: { rejectUnauthorized: false }
})
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.static("public"));
app.locals.title = "onlyDevs API"
app.get("/questions", (request, response) => {
pool.query("SELECT * FROM questions", (error, results) => {
if (error) {
throw error
}
return response.status(200).json(results.rows);
});
});
app.post("/questions", (request, response) => {
const { question } = request.body;
pool.query("INSERT INTO questions(question) VALUES ($1)",
[question]
);
return response.status(200);
});
app.get('/questions/:id', (request, response) => {
const { id } = request.params
pool.query(`SELECT * FROM ANSWERS WHERE question_id = ${id}`, (error, results) => {
if (error) {
throw error
}
return response.status(200).json(results.rows);
});
});
app.post('/questions/answer', (request, response) => {
const { question_id, answer } = request.body;
pool.query('INSERT INTO answers(question_id, answer, rating) VALUES ($1, $2, $3)',
[question_id, answer, 0]
);
return response.status(201).json("Successful post");
})
app.post('/questions/answer/vote', (request, response) => {
const { question_id, answer_id, vote } = request.body
if (vote === 'upvote') {
pool.query(`UPDATE answers SET rating = rating + 1 WHERE question_id = ${question_id} AND id = ${answer_id}`)
}
else if (vote === 'downvote') {
pool.query(`UPDATE answers SET rating = rating - 1 WHERE question_id = ${question_id} AND id = ${answer_id}`)
};
return response.status(201).json("Successful post")
})
app.listen(process.env.PORT || 3001, () => {
console.log("Server is running.");
});