-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
94 lines (79 loc) · 2.25 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
require('dotenv').config();
const { Pool } = require('pg');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const nodeCleanup = require('node-cleanup');
const config = require('./config');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
const app = express();
app.use(cors({ methods: ['GET'] }));
app.use(bodyParser.json({ type: 'application/json' }));
const historyRouter = express.Router();
historyRouter.get('/', async (req, res) => {
try {
const { query } = req;
const {
account,
offset,
limit,
type,
symbol,
} = query;
let sOffset = parseInt(offset, 10);
if (isNaN(sOffset)) { // eslint-disable-line no-restricted-globals
sOffset = 0;
}
let sLimit = parseInt(limit, 10);
if (isNaN(sLimit)) { // eslint-disable-line no-restricted-globals
sLimit = 500;
} else if (sLimit > 500) {
sLimit = 500;
} else if (sLimit <= 0) {
sLimit = 1;
}
const sType = type !== 'user' && type !== 'contract' ? 'user' : type;
if (symbol) {
const SQLQuery = `
SELECT *
FROM "transactions"
WHERE
(
("from" = $1 AND "from_type" = $2) OR
("to" = $1 AND "to_type" = $2)
) AND
"symbol" = $3
ORDER BY "timestamp" DESC
OFFSET $4
LIMIT $5`;
const { rows } = await pool.query(SQLQuery, [account, sType, symbol, sOffset, sLimit]);
return res.status(200).json(rows);
}
const SQLQuery = `
SELECT *
FROM "transactions"
WHERE
("from" = $1 AND "from_type" = $2) OR
("to" = $1 AND "to_type" = $2)
ORDER BY "timestamp" DESC
OFFSET $3
LIMIT $4`;
const { rows } = await pool.query(SQLQuery, [account, sType, sOffset, sLimit]);
return res.status(200).json(rows);
} catch (err) {
console.error(err); // eslint-disable-line no-console
return res.status(400).json({
errors: ['an error occured'],
});
}
});
app.use('/history', historyRouter);
app.set('trust proxy', true);
app.set('trust proxy', 'loopback');
app.listen(config.port);
// graceful app closing
nodeCleanup((exitCode, signal) => { // eslint-disable-line no-unused-vars
pool.end();
});