-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreceive-reqs.consumer.mjs
More file actions
85 lines (70 loc) · 1.94 KB
/
receive-reqs.consumer.mjs
File metadata and controls
85 lines (70 loc) · 1.94 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { connect } from "amqplib";
import { DatabaseSync } from "node:sqlite";
import sqlBricks from "sql-bricks";
const db = new DatabaseSync(":memory:");
let dbAlreadyExists = false;
export function insert(queryParams) {
const { table, items } = queryParams;
const { text, values } = sqlBricks
.insertInto(table, items)
.toParams({ placeholder: "?" });
const insertStatement = db.prepare(text);
insertStatement.run(...values);
}
export function select(query) {
return db.prepare(query).all();
}
function prepareDb() {
db.exec(`
DROP TABLE IF EXISTS reqs
`);
db.exec(`
CREATE TABLE reqs(
id INTEGER PRIMARY KEY AUTOINCREMENT,
method TEXT NOT NULL,
ip TEXT NOT NULL,
resourceUrl TEXT,
time TEXT NOT NULL
) STRICT
`);
dbAlreadyExists = true;
}
function createConnection() {
return (async () => {
const connection = await connect({
username: "user",
password: "password",
port: 5672
});
return await connection.createChannel();
})();
}
async function ReceiveReqs() {
await createConnection().then((channel) => {
console.log("RabbitMq Consumer already is running...");
channel.assertQueue("receiveReqs");
channel.consume("receiveReqs", (msg) => {
if (msg) {
const incommingData = msg.content.toString();
const getRequests = JSON.parse(incommingData);
try {
if (!dbAlreadyExists) prepareDb();
insert({ table: "reqs", items: getRequests });
channel.ack(msg);
const selectReqsQuery = sqlBricks
.select("ip,method,resourceUrl,time")
.orderBy("method")
.from("reqs")
.toString();
const reply = select(selectReqsQuery);
for (const req of reply) {
console.log(req);
}
} catch (error) {
console.log(error);
}
}
});
});
}
ReceiveReqs();