-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
83 lines (68 loc) · 2.27 KB
/
api.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
71
72
73
74
75
76
77
78
79
80
81
82
83
import * as process from "process";
import fastify from "fastify";
import { createPool } from "slonik";
import { SlonikMigrator } from "@slonik/migrator";
import { setupDB } from "./db.js";
import { setupSeenByStrategy } from "./strategy.js";
/**
* Build the example API application
*
* @returns The fastify application that was built
*/
export async function buildAPI(args) {
// Set up the application
const app = fastify({
disableRequestLogging: typeof args?.logRequests === "boolean" ? args.logRequests : true,
logger: {
level: args?.logLevel ?? process.env.LOG_LEVEL ?? "info",
},
});
// Build the seen by strategy
const seenByStrategy = await setupSeenByStrategy({
logger: app.log,
strategy: process.env.SEEN_BY_STRATEGY,
});
// Set up the database
const db = await setupDB({
logger: app.log,
dbURL: process.env.DB_URL,
seenByStrategy,
});
app.db = db; // Save the DB to the application
// Retrieve the count and/or who has seen a given post
app.get('/posts/:postId/seen-by/count', async (req, res) => {
const postId = req.params.postId;
req.log.debug(`handling noitifications fetch for post with ID [${postId}]`);
// Retrieve how many times (+/- by whom) an post has been seen
const seenBy = await seenByStrategy.getSeenByCountForPost({
db,
postId: postId,
});
return seenBy;
});
// Retrieve the users who have seen a given post
app.get('/posts/:postId/seen-by/users', async (req, res) => {
const postId = req.params.postId;
req.log.debug(`handling noitifications fetch for post with ID [${postId}]`);
// Retrieve how many times (+/- by whom) an post has been seen
const seenBy = await seenByStrategy.getSeenByUsersForPost({
db,
postId: postId,
});
return seenBy;
});
// Record that a given post was seen
app.post('/posts/:postId/seen-by/:userId', async (req, res) => {
const postId = req.params.postId;
const userId = req.params.userId;
req.log.debug(`adding notification for post [${postId}] by user [${userId}]`);
// Record that the post (in this case a post) has been seen
await seenByStrategy.recordSeenByForPost({
db,
postId: postId,
userId: userId,
});
return { ok: true };
});
return app;
}