-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
125 lines (117 loc) · 3.09 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
const fastify = require('fastify')({ logger: true })
const sql = require('mssql')
const sqlConfig = {
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
server: process.env.DB_HOST,
options: {
encrypt: false,
trustServerCertificate: true
},
driver: "msnodesqlv8",
}
/*
PROCESSING STATS
*/
fastify.get('/processing-stats', async function handler(request, reply) {
try {
const result = await sql.query(`select sum(SubjectsProcessed) as MatchingEvents from ProcessingStats`);
if (result.recordset[0].MatchingEvents == null) {
result.recordset[0].MatchingEvents = 0
}
reply.code(200)
reply.send(result.recordset[0])
return reply
} catch (err) {
console.error(err);
reply.code(500)
reply.send(err)
return reply
}
})
fastify.delete('/processing-stats', async function handler(request, reply) {
try {
const result = await sql.query(`TRUNCATE TABLE ProcessingStats`);
reply.code(204)
return reply
} catch (err) {
reply.code(500)
reply.send(err)
return reply
}
})
/*
DATABASE CONNECTION
*/
fastify.post('/database', async function handler(request, reply) {
try {
sql.connect(sqlConfig)
reply.code(200)
reply.send({
"status": "connected",
"message": ""
})
return reply
} catch (err) {
reply.code(500)
reply.send({
"status": "error",
"message": err
})
return reply
}
})
fastify.get('/database', async function handler(request, reply) {
try {
const result = await sql.query(``)
reply.code(204)
reply.send({
"status": "connected",
"message": ""
})
return reply
} catch (err) {
switch (err.code) {
case "ENOCONN":
reply.code(503)
reply.send({
"status": "disconnected",
"message": "Unable to reach database server."
})
break
case "ECONNCLOSED":
reply.code(205)
reply.send({
"status": "connecting",
"message": "Connection attempt in progress."
})
break
default:
reply.code(500)
reply.send({
"status": "error",
"message": err
})
}
return reply
}
})
fastify.register(require('@fastify/cors'), (instance) => {
return (req, callback) => {
const corsOptions = {
// This is NOT recommended for production as it enables reflection exploits
origin: "*"
};
// callback expects two parameters: error and options
callback(null, corsOptions)
}
})
// Run the server!
fastify.listen({port: 3000, host: "0.0.0.0" }, (err) => {
if (err) {
fastify.log.error(err)
}
sql.connect(sqlConfig)
.catch(console.error);
})