forked from rmt-22-verona-fox/p2-iproject-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
84 lines (65 loc) · 1.96 KB
/
app.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
"use strict";
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
const cors = require("cors");
const express = require("express");
const app = express();
const routes = require("./routes/index");
const { errorHandler } = require("./middlewares/errorHandler");
const axios = require("axios");
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.use(routes);
const { createServer } = require("http");
const { Server } = require("socket.io");
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: "http://localhost:8080",
},
});
let users = [];
let chats = [];
io.on("connection", (socket) => {
console.log("a user connected");
socket.on("disconnect", () => {
console.log("a user disconnected");
});
socket.on("customEventFromClient", (payload) => {
console.log("request from client", payload);
});
socket.emit("customEventFromServer", "response from server");
socket.on("setUsername", (payload) => {
users.push({ username: payload, status: "online" });
});
socket.on("sendMessageToServer", (payload) => {
if (payload && payload.message) {
chats.push(payload);
}
io.emit("receivedMessageFromServer", chats);
});
socket.on("sendPokemonToTrade", async (payload) => {
const { data } = await axios.get(
`https://pokeapi.co/api/v2/pokemon/${payload.PokemonId}`
);
payload.imageUrl = data.sprites.other["official-artwork"].front_default;
payload.pokemonName = data.name;
chats.push(payload);
io.emit("receivedMessageFromServer", chats);
});
socket.on("incrementConfirmCount", () => {
io.emit("incrementConfirmCountServer");
});
socket.on("completeTrade", () => {
chats = [];
io.emit("receivedMessageFromServer", chats);
io.emit("completeTradeServer");
});
});
httpServer.listen(3001, () => {
console.log("listening on *:3001");
});
app.use(errorHandler);
module.exports = app;