-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactivity.js
80 lines (65 loc) · 2.06 KB
/
activity.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
const utils = require('./utils.js');
const tokenManager = require('./token.js');
const TABLE = process.env.VISIT_TABLE;
if (!TABLE) {
throw "Invalid table name. Check env var is set.";
}
const QUERY_FIELDS = "id, token_id, INET_NTOA(address) AS address, user_agent, created";
const queryGetAll = (tokenId, limit) => `SELECT ${QUERY_FIELDS} FROM ${TABLE} ${!tokenId ? "" : "WHERE token_id = ?"} ORDER BY created DESC ${!limit ? "" : "LIMIT ?"};`;
const queryNew = () => `INSERT INTO ${TABLE} (token_id, address, user_agent) VALUES (?, INET_ATON(?), ?);`;
module.exports.getActivity = (con, tokenId, limit, callback) => {
if (!con) {
callback("INVALID_CONNECTION", false);
return;
}
if (!utils.validateId(tokenId)) {
callback("INVALID_TOKEN_ID", false);
return;
}
if (!utils.validateLimit(limit)) {
callback("INVALID_LIMIT", false);
return;
}
tokenManager.getKey(con, tokenId, (qerr, tres) => {
if (qerr || !tres) {
console.error("ERROR: Failed to get corresponding key for activity:", qerr);
callback("GET_TOKEN_FAILED", false);
return;
}
con.query(queryGetAll(true, true), [tokenId, limit], (qerr, res) => {
if (qerr || !res) {
console.error("ERROR: Failed to get activity data:", qerr);
callback("GET_VISITS_FAILED", false);
return;
}
if (res.length <= 0) {
console.warn("No activity found for token id:", tres.id);
callback(null, []);
return;
}
for (var i = 0; i < res.length; i++) {
res[i].token = tres;
}
callback(null, res);
});
});
};
module.exports.addActivity = (con, data, callback) => {
if (!con) {
console.error("ERROR: Invalid connection provided.");
callback("INVALID_CONNECTION", false);
return;
}
if (!utils.validateId(data.token.id)) {
console.error("ERROR: Invalid token ID provided.");
callback("INVALID_TOKEN_ID", false);
return;
}
con.query(queryNew(), [data.token.id, data.info.address, data.info.userAgent], (qerr, res) => {
if (qerr || !res) {
console.error("ERROR: Failed to add new activity entry:", qerr);
callback(qerr, false);
return;
}
});
};