-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
80 lines (75 loc) · 2.22 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
// Require the framework and instantiate it
const mysql = require('mysql2/promise');
require('dotenv').config()
const fastify = require('fastify')({ logger: false })
const port = process.env.PORT || 3000
const nuxtRoutes = require('./.nuxt/routes.json');
fastify.register(require('fastify-websocket'))
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: process.env.DB_PASSWD,
database: 'db',
port: 3306
});
console.log("Connected!")
fastify.register(require('fastify-nuxtjs')).after(() => {
nuxtRoutes.forEach((nuxtRoute) => {
fastify.nuxt(nuxtRoute.path);
})
})
const start = async () => {
try {
await fastify.listen(port)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
fastify.register(require('fastify-static'), {
root: __dirname,
prefix: '/', // optional: default '/'
})
fastify.get('/entry', function (req, reply) {
return reply.sendFile('./entry/index.html')
})
fastify.get('/api/get/universidades', async function (req, reply) {
return reply.send(await dbQuery("SELECT DISTINCT universidad FROM `facultades`"))
})
fastify.get('/api/get/carreras', function (req, reply) {
return reply.send()
})
fastify.get('/api/get/Universidades', function (req, reply) {
return reply.send()
})
function dbQuery(dataExpression) {
return pool.query(dataExpression)
}
fastify.get('/wss/', { websocket: true }, async (connection /* SocketStream */, req /* FastifyRequest */) => {
console.log("client connected!");
connection.socket.send(JSON.stringify({
operation: "wssUpdate",
content: {
universidades: await dbQuery("SELECT DISTINCT universidad FROM `facultades`"),
data: await dbQuery("SELECT * from `examenes`")
}
}))
connection.socket.on('message', async message => {
let msg = JSON.parse(message)
if (msg.operation == "getFromDb") {
connection.socket.send(JSON.stringify({
operation: "updateFromDb",
context: msg.context,
get: msg.get,
content: await dbQuery(msg.content)
}))
}
if(msg.operation == "sendToDb" /* TODO on production origin check*/){
let response = await dbQuery(msg.content)
connection.socket.send(JSON.stringify({
response: response
}))
}
})
})
start()