Commit 2cc5435c authored by Vũ Gia Vương's avatar Vũ Gia Vương

update try catch, get user by userId

parent 0ab5c370
...@@ -25,6 +25,7 @@ let matchId = ''; ...@@ -25,6 +25,7 @@ let matchId = '';
let eventId = null; let eventId = null;
function startGameApi(data) { function startGameApi(data) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try {
timeStart = new Date().getTime(); timeStart = new Date().getTime();
userId = (Math.random() * 100 >> 0) + 10; userId = (Math.random() * 100 >> 0) + 10;
matchId = `${userId}-${GAME_CODE}-${timeStart}`; matchId = `${userId}-${GAME_CODE}-${timeStart}`;
...@@ -34,10 +35,15 @@ function startGameApi(data) { ...@@ -34,10 +35,15 @@ function startGameApi(data) {
}; };
const result = yield callApi(URL_START_GAME, 'POST', data); const result = yield callApi(URL_START_GAME, 'POST', data);
return result; return result;
}
catch (error) {
console.log('error', error);
}
}); });
} }
function endGameApi(user) { function endGameApi(user) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try {
const playedSeconds = (new Date().getTime() - timeStart) / 1e3; const playedSeconds = (new Date().getTime() - timeStart) / 1e3;
const details = user.history.map(h => ({ const details = user.history.map(h => ({
level: h.tower, level: h.tower,
...@@ -55,6 +61,11 @@ function endGameApi(user) { ...@@ -55,6 +61,11 @@ function endGameApi(user) {
details details
}; };
const res = yield callApi(URL_END_GAME, 'POST', params); const res = yield callApi(URL_END_GAME, 'POST', params);
return res;
}
catch (error) {
console.log('error', error);
}
}); });
} }
function callApi(url, method, data) { function callApi(url, method, data) {
...@@ -69,11 +80,10 @@ function callApi(url, method, data) { ...@@ -69,11 +80,10 @@ function callApi(url, method, data) {
body: JSON.stringify(data), body: JSON.stringify(data),
}); });
const result = yield res.json(); const result = yield res.json();
console.log(url, result.code, result.message);
return (result === null || result === void 0 ? void 0 : result.code) == 'success'; return (result === null || result === void 0 ? void 0 : result.code) == 'success';
} }
catch (error) { catch (error) {
console.log('error call api: ', error); console.log('error callApi: ', error);
} }
}); });
} }
...@@ -5,7 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) { ...@@ -5,7 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const v2_1 = __importDefault(require("./v2")); const v2_1 = __importDefault(require("./v2"));
class User { class User {
constructor(token) { constructor(token, id) {
this.id = '';
this.token = ''; this.token = '';
this.towerNumber = 0; this.towerNumber = 0;
this.direction = 1; this.direction = 1;
...@@ -21,6 +22,7 @@ class User { ...@@ -21,6 +22,7 @@ class User {
this.isEndGame = true; this.isEndGame = true;
this.history = []; this.history = [];
this.token = token; this.token = token;
this.id = id;
this.reset(); this.reset();
} }
reset() { reset() {
......
...@@ -21,3 +21,9 @@ const io = new socket_io_1.Server(server, { ...@@ -21,3 +21,9 @@ const io = new socket_io_1.Server(server, {
server.listen(PORT, () => { server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}!`); console.log(`Server is running on port ${PORT}!`);
}); });
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
...@@ -34,13 +34,15 @@ const CONFIG = { ...@@ -34,13 +34,15 @@ const CONFIG = {
} }
}; };
function setupSocket(io) { function setupSocket(io) {
try {
io.use((socket, next) => { io.use((socket, next) => {
const token = String(socket.handshake.query.token); const token = String(socket.handshake.query.token);
if (!token) { const userId = String(socket.handshake.query.userId);
if (!token || !userId) {
return; return;
} }
if (!users.has(token)) { if (!users.has(userId)) {
users.set(token, new User_1.default(token)); users.set(userId, new User_1.default(token, userId));
} }
next(); next();
}); });
...@@ -52,15 +54,24 @@ function setupSocket(io) { ...@@ -52,15 +54,24 @@ function setupSocket(io) {
socket.on(CONFIG.EVT.END_GAME, () => endGame(socket)); socket.on(CONFIG.EVT.END_GAME, () => endGame(socket));
socket.on("disconnect", () => onDisconnect(socket)); socket.on("disconnect", () => onDisconnect(socket));
}); });
}
catch (error) {
console.log('error', error);
}
} }
function endGame(socket) { function endGame(socket) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try {
const user = getUserBySocket(socket); const user = getUserBySocket(socket);
user.reset(); user.reset();
if (user === null || user === void 0 ? void 0 : user.isEndGame) { if (user === null || user === void 0 ? void 0 : user.isEndGame) {
return; return;
} }
(0, networkCtrl_1.endGameApi)(user); (0, networkCtrl_1.endGameApi)(user);
}
catch (error) {
console.log('error', error);
}
}); });
} }
function onDisconnect(socket) { function onDisconnect(socket) {
...@@ -75,6 +86,7 @@ function getHistory(socket) { ...@@ -75,6 +86,7 @@ function getHistory(socket) {
} }
function startGame(socket, data) { function startGame(socket, data) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try {
const user = getUserBySocket(socket); const user = getUserBySocket(socket);
const result = yield (0, networkCtrl_1.startGameApi)(data); const result = yield (0, networkCtrl_1.startGameApi)(data);
// const result = true; // const result = true;
...@@ -87,10 +99,15 @@ function startGame(socket, data) { ...@@ -87,10 +99,15 @@ function startGame(socket, data) {
console.log('start game fail'); console.log('start game fail');
socket.emit(CONFIG.EVT.REQUEST_START_GAME, false); socket.emit(CONFIG.EVT.REQUEST_START_GAME, false);
} }
}
catch (error) {
console.log('error', error);
}
}); });
} }
function passTower(socket, data) { function passTower(socket, data) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try {
const user = getUserBySocket(socket); const user = getUserBySocket(socket);
const xDistance_ = data.distance; const xDistance_ = data.distance;
const { direction, nextBlock, towerNumber, position } = user; const { direction, nextBlock, towerNumber, position } = user;
...@@ -154,10 +171,15 @@ function passTower(socket, data) { ...@@ -154,10 +171,15 @@ function passTower(socket, data) {
user.reset(); user.reset();
console.log('END'); console.log('END');
} }
}
catch (error) {
console.log('error', error);
}
}); });
} }
function addBlock(socket) { function addBlock(socket) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try {
const user = getUserBySocket(socket); const user = getUserBySocket(socket);
const towerNumber = ++user.towerNumber; const towerNumber = ++user.towerNumber;
const xDistance = ((Math.min(towerNumber, 100) / 100 + 1) + Math.random() * (towerNumber <= 10 ? 0.5 : 1)) * 150; const xDistance = ((Math.min(towerNumber, 100) / 100 + 1) + Math.random() * (towerNumber <= 10 ? 0.5 : 1)) * 150;
...@@ -179,9 +201,13 @@ function addBlock(socket) { ...@@ -179,9 +201,13 @@ function addBlock(socket) {
}; };
user.timeStart = Date.now(); user.timeStart = Date.now();
socket.emit(CONFIG.EVT.REQUEST_SPAWN_TOWER, data); socket.emit(CONFIG.EVT.REQUEST_SPAWN_TOWER, data);
}
catch (error) {
console.log('error', error);
}
}); });
} }
function getUserBySocket(socket) { function getUserBySocket(socket) {
const token = String(socket.handshake.query.token); const userId = String(socket.handshake.query.userId);
return users.get(token); return users.get(userId);
} }
...@@ -15,6 +15,7 @@ let matchId = ''; ...@@ -15,6 +15,7 @@ let matchId = '';
let eventId: string | null = null; let eventId: string | null = null;
export async function startGameApi(data: any) { export async function startGameApi(data: any) {
try {
timeStart = new Date().getTime(); timeStart = new Date().getTime();
userId = (Math.random() * 100 >> 0) + 10; userId = (Math.random() * 100 >> 0) + 10;
matchId = `${userId}-${GAME_CODE}-${timeStart}`; matchId = `${userId}-${GAME_CODE}-${timeStart}`;
...@@ -25,11 +26,15 @@ export async function startGameApi(data: any) { ...@@ -25,11 +26,15 @@ export async function startGameApi(data: any) {
}; };
const result = await callApi(URL_START_GAME, 'POST', data); const result = await callApi(URL_START_GAME, 'POST', data);
return result; return result;
} catch (error) {
console.log('error', error)
}
} }
export async function endGameApi(user: User) { export async function endGameApi(user: User) {
try {
const playedSeconds = (new Date().getTime() - timeStart) / 1e3; const playedSeconds = (new Date().getTime() - timeStart) / 1e3;
const details = user.history.map(h=>({ const details = user.history.map(h => ({
level: h.tower, level: h.tower,
score: h.score, score: h.score,
timeStart: h.timeStart, timeStart: h.timeStart,
...@@ -47,6 +52,10 @@ export async function endGameApi(user: User) { ...@@ -47,6 +52,10 @@ export async function endGameApi(user: User) {
} }
const res = await callApi(URL_END_GAME, 'POST', params); const res = await callApi(URL_END_GAME, 'POST', params);
return res;
} catch (error) {
console.log('error', error)
}
} }
async function callApi(url: string, method: string, data: any) { async function callApi(url: string, method: string, data: any) {
...@@ -60,10 +69,9 @@ async function callApi(url: string, method: string, data: any) { ...@@ -60,10 +69,9 @@ async function callApi(url: string, method: string, data: any) {
body: JSON.stringify(data), body: JSON.stringify(data),
}); });
const result = await res.json(); const result = await res.json();
console.log(url, result.code, result.message);
return result?.code == 'success'; return result?.code == 'success';
} catch (error) { } catch (error) {
console.log('error call api: ', error); console.log('error callApi: ', error);
} }
} }
import v2 from "./v2"; import v2 from "./v2";
class User { class User {
public id: string = '';
public token: string = ''; public token: string = '';
public towerNumber: number = 0; public towerNumber: number = 0;
public direction: number = 1; public direction: number = 1;
...@@ -10,17 +11,18 @@ class User { ...@@ -10,17 +11,18 @@ class User {
public totalScore: number = 0; public totalScore: number = 0;
public combo: number = 0; public combo: number = 0;
public curBlock: v2 = new v2(0,0); public curBlock: v2 = new v2(0, 0);
public nextBlock: v2 = new v2(0,0); public nextBlock: v2 = new v2(0, 0);
public screenPos: v2 = new v2(0,0); public screenPos: v2 = new v2(0, 0);
public position: v2 = new v2(0,0); public position: v2 = new v2(0, 0);
public timeStart: number = 0; public timeStart: number = 0;
public isEndGame: boolean = true; public isEndGame: boolean = true;
public history: History[] = []; public history: History[] = [];
constructor(token: string) { constructor(token: string, id: string) {
this.token = token; this.token = token;
this.id = id;
this.reset(); this.reset();
} }
...@@ -61,14 +63,6 @@ export interface IDataPassTower { ...@@ -61,14 +63,6 @@ export interface IDataPassTower {
totalScore: number, totalScore: number,
} }
// {
// nextBlock: user.nextBlock,
// screenPos: user.screenPos,
// direction: user.direction,
// distance2Tower: user.distance2Tower,
// towerNumber: user.towerNumber - 1,
// };
export interface IDataSpawnTower { export interface IDataSpawnTower {
nextBlock: v2, nextBlock: v2,
screenPos: v2, screenPos: v2,
...@@ -77,4 +71,9 @@ export interface IDataSpawnTower { ...@@ -77,4 +71,9 @@ export interface IDataSpawnTower {
towerNumber: number, towerNumber: number,
} }
export interface IQuery {
token?: string,
userId?: string
}
export default User; export default User;
\ No newline at end of file
...@@ -20,4 +20,12 @@ setupSocket(io); ...@@ -20,4 +20,12 @@ setupSocket(io);
server.listen(PORT, () => { server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}!`); console.log(`Server is running on port ${PORT}!`);
}) });
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
...@@ -22,13 +22,15 @@ const CONFIG = { ...@@ -22,13 +22,15 @@ const CONFIG = {
}; };
export function setupSocket(io: Server) { export function setupSocket(io: Server) {
try {
io.use((socket: Socket, next) => { io.use((socket: Socket, next) => {
const token = String(socket.handshake.query.token); const token = String(socket.handshake.query.token);
if (!token) { const userId = String(socket.handshake.query.userId);
if (!token || !userId) {
return; return;
} }
if (!users.has(token)) { if (!users.has(userId)) {
users.set(token, new User(token)); users.set(userId, new User(token, userId));
} }
next(); next();
}); });
...@@ -44,9 +46,13 @@ export function setupSocket(io: Server) { ...@@ -44,9 +46,13 @@ export function setupSocket(io: Server) {
socket.on("disconnect", () => onDisconnect(socket)); socket.on("disconnect", () => onDisconnect(socket));
}); });
} catch (error) {
console.log('error', error)
}
} }
async function endGame(socket: Socket) { async function endGame(socket: Socket) {
try {
const user = getUserBySocket(socket); const user = getUserBySocket(socket);
user.reset(); user.reset();
...@@ -54,6 +60,9 @@ async function endGame(socket: Socket) { ...@@ -54,6 +60,9 @@ async function endGame(socket: Socket) {
return; return;
} }
endGameApi(user); endGameApi(user);
} catch (error) {
console.log('error', error)
}
} }
function onDisconnect(socket: Socket): void { function onDisconnect(socket: Socket): void {
...@@ -67,6 +76,7 @@ async function getHistory(socket: Socket) { ...@@ -67,6 +76,7 @@ async function getHistory(socket: Socket) {
} }
async function startGame(socket: Socket, data: any) { async function startGame(socket: Socket, data: any) {
try {
const user = getUserBySocket(socket); const user = getUserBySocket(socket);
const result = await startGameApi(data); const result = await startGameApi(data);
// const result = true; // const result = true;
...@@ -78,9 +88,13 @@ async function startGame(socket: Socket, data: any) { ...@@ -78,9 +88,13 @@ async function startGame(socket: Socket, data: any) {
console.log('start game fail'); console.log('start game fail');
socket.emit(CONFIG.EVT.REQUEST_START_GAME, false); socket.emit(CONFIG.EVT.REQUEST_START_GAME, false);
} }
} catch (error) {
console.log('error', error)
}
} }
async function passTower(socket: Socket, data: { distance: number }) { async function passTower(socket: Socket, data: { distance: number }) {
try {
const user = getUserBySocket(socket); const user = getUserBySocket(socket);
const xDistance_ = data.distance; const xDistance_ = data.distance;
...@@ -157,9 +171,13 @@ async function passTower(socket: Socket, data: { distance: number }) { ...@@ -157,9 +171,13 @@ async function passTower(socket: Socket, data: { distance: number }) {
user.reset(); user.reset();
console.log('END'); console.log('END');
} }
} catch (error) {
console.log('error', error)
}
} }
async function addBlock(socket: Socket) { async function addBlock(socket: Socket) {
try {
const user = getUserBySocket(socket); const user = getUserBySocket(socket);
const towerNumber = ++user.towerNumber; const towerNumber = ++user.towerNumber;
...@@ -184,9 +202,12 @@ async function addBlock(socket: Socket) { ...@@ -184,9 +202,12 @@ async function addBlock(socket: Socket) {
}; };
user.timeStart = Date.now(); user.timeStart = Date.now();
socket.emit(CONFIG.EVT.REQUEST_SPAWN_TOWER, data); socket.emit(CONFIG.EVT.REQUEST_SPAWN_TOWER, data);
} catch (error) {
console.log('error', error)
}
} }
function getUserBySocket(socket: Socket) { function getUserBySocket(socket: Socket) {
const token = String(socket.handshake.query.token); const userId = String(socket.handshake.query.userId);
return users.get(token)!; return users.get(userId)!;
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment