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