-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathserver.js
69 lines (58 loc) · 1.72 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
"use strict";
const fastify = require("fastify");
const connectionString =
process.env.DATABASE_URL ||
"postgresql://postgres:postgres@localhost:5432/fastify_postgres?schema=public";
function build(opts = {}) {
const app = fastify(opts);
app.register(require("fastify-postgres"), { connectionString });
app.get("/", async () => {
const client = await app.pg.connect();
const { rows } = await client.query("SELECT * FROM books");
client.release();
return rows;
});
app.post("/", async (request) => {
const { body } = request;
const client = await app.pg.connect();
const { rows } = await client.query(
"INSERT INTO books (title) VALUES ($1) RETURNING *",
[body.title]
);
client.release();
return rows;
});
app.get("/:id", async (request) => {
const { params } = request;
const client = await app.pg.connect();
const { rows } = await client.query("SELECT * FROM books WHERE id = $1", [
+params.id,
]);
client.release();
return rows;
});
app.patch("/:id", async (request) => {
const { params, body } = request;
return app.pg.transact(async (client) => {
await client.query("UPDATE books SET title = $1 WHERE id = $2", [
body.title,
+params.id,
]);
const { rows } = await client.query("SELECT * FROM books WHERE id = $1", [
+params.id,
]);
return rows;
});
});
app.delete("/:id", async (request) => {
const { params } = request;
const client = await app.pg.connect();
const { rowCount } = await client.query("DELETE FROM books WHERE id = $1", [
+params.id,
]);
client.release();
return { rowCount };
});
return app;
}
module.exports = build;