Skip to content

Commit

Permalink
FIX:GAME (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
automerge-pingpong[bot] authored and root committed Nov 14, 2023
2 parents c90eb3a + 471f3dd commit 720e15c
Show file tree
Hide file tree
Showing 13 changed files with 484 additions and 1,608 deletions.
428 changes: 265 additions & 163 deletions backend/code/src/game/game.ts

Large diffs are not rendered by default.

52 changes: 38 additions & 14 deletions backend/code/src/gateways/gateways.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {} from '@nestjs/platform-socket.io';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { PrismaService } from 'src/prisma/prisma.service';
import { Game } from 'src/game/game';
import { $Enums, Notification , Match } from '@prisma/client';
import { $Enums, Notification } from '@prisma/client';

@WebSocketGateway(3004, {
cors: {
Expand Down Expand Up @@ -211,7 +211,7 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
// }
@OnEvent('game.launched')
async handleGameLaunchedEvent(clients: any) {
const game_channel = `Game:${clients[0].socket.id}:${clients[1].socket.id}`;
const game_channel = `Game:${clients[0].socket.id}:${clients[1].socket.id}`;
console.log(game_channel);
clients.forEach((client: any) => {
client.socket.join(game_channel);
Expand All @@ -234,18 +234,42 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
console.log('game ended');
console.log(data);
this.server.to(data.gameid).emit('game.end', data);
console.log(data)

await this.prisma.match.create({
data: {
participant1Id: data.p1Data.userId,
participant2Id: data.p2Data.userId,
winner_id: data.p1Score > data.p2Score ? data.p1Data.userId : data.p2Data.userId ,
score1: data.p1Score,
score2: data.p2Score,
},
});

console.log(data);
if (data.resign === 0) {
await this.prisma.match.create({
data: {
participant1Id: data.p1Data.userId,
participant2Id: data.p2Data.userId,
winner_id:
data.p1Score > data.p2Score
? data.p1Data.userId
: data.p2Data.userId,
score1: data.p1Score,
score2: data.p2Score,
},
});
} else if (data.resign === 1) {
await this.prisma.match.create({
data: {
participant1Id: data.p1Data.userId,
participant2Id: data.p2Data.userId,
winner_id: data.p2Data.userId,
score1: 0,
score2: 5,
},
});
} else if (data.resign === 2) {
await this.prisma.match.create({
data: {
participant1Id: data.p1Data.userId,
participant2Id: data.p2Data.userId,
winner_id: data.p1Data.userId,
score1: 5,
score2: 0,
},
});
}

this.games_map.delete(data.gameid);
}

Expand Down
8 changes: 4 additions & 4 deletions backend/code/src/profile/profile.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ export class ProfileService {
wonMatches === 0
? null
: wonMatches >= 100
? 2
: Math.floor(Math.log10(wonMatches));
? 2
: Math.floor(Math.log10(wonMatches));

return new ProfileDto({ ...user, achievement }, false);
}
Expand Down Expand Up @@ -58,8 +58,8 @@ export class ProfileService {
wonMatches === 0
? null
: wonMatches >= 100
? 2
: Math.floor(Math.log10(wonMatches));
? 2
: Math.floor(Math.log10(wonMatches));
return new ProfileDto({ ...user, achievement }, true);
}

Expand Down
1 change: 1 addition & 0 deletions docker-compose-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ services :
networks:
- pongnet
backend:
container_name: backend
build:
context: ./backend
dockerfile: Dockerfile.dev
Expand Down
118 changes: 99 additions & 19 deletions frontend/code/src/Api/base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import axios from "axios";
// const navigate = useNavigate();
// return navigate;
// };
const api = axios.create({

const apiWithoutManager = axios.create({
baseURL: `${process.env.REACT_APP_API_ENDPOINT}`,
timeout: 10000,
withCredentials: true,
Expand All @@ -15,26 +16,105 @@ const api = axios.create({
},
});

let refreshAttempted = 0;

const errorHandler = async (error: any) => {

if (error?.response?.status === 401) {
if (refreshAttempted <= 2) {
const ConcurrencyManager = (axios: any, MAX_CONCURRENT = 10) => {
if (MAX_CONCURRENT < 1){
//eslint-disable-next-line
throw "Concurrency Manager Error: minimun concurrent requests is 1";
}
let instance = {
queue: [] as any[],
running: [] as any[],
shiftInitial: () => {
setTimeout(() => {
if (instance.running.length < MAX_CONCURRENT) {
instance.shift();
}
}, 0);
},
push: (reqHandler: any) => {
instance.queue.push(reqHandler);
instance.shiftInitial();
},
shift: () => {
if (instance.queue.length) {
const queued = instance.queue.shift();
queued.resolver(queued.request);
instance.running.push(queued);
}
},
// Use as interceptor. Queue outgoing requests
requestHandler: (req: any) => {
return new Promise(resolve => {
instance.push({ request: req, resolver: resolve });
});
},
// Use as interceptor. Execute queued request upon receiving a response
responseHandler: (res: any) => {
instance.running.shift();
instance.shift();
return res;
},
responseErrorHandler: async (error: any) => {
if (error?.response?.status === 401) {
try {
refreshAttempted++;
await api.get("auth/refresh");
return api.request(error.config);
} catch (refreshError) {}
} else {
refreshAttempted--;
const refreshError = await apiWithoutManager.get("auth/refresh").then(() => null).catch((err: any) => err);
if (refreshError && window.location.pathname !== '/') {
instance.queue = [];
instance.running = [];
window.location.href = '/';
return;
}
const res = await apiWithoutManager.request(error.config);
return instance.responseHandler(res);
} catch (refreshError) { }
}
return Promise.reject(instance.responseHandler(error));
},
interceptors: {
request: null,
response: null
},
detach: () => {
axios.interceptors.request.eject(instance.interceptors.request);
axios.interceptors.response.eject(instance.interceptors.response);
}
return Promise.reject(error);
};
api.interceptors.response.use(
(response) => response,
(error) => errorHandler(error)
// queue concurrent requests
instance.interceptors.request = axios.interceptors.request.use(
instance.requestHandler
);

export default api;
instance.interceptors.response = axios.interceptors.response.use(
instance.responseHandler,
instance.responseErrorHandler,
);
return instance;
};

const api = axios.create({
baseURL: `${process.env.REACT_APP_API_ENDPOINT}`,
timeout: 10000,
withCredentials: true,
headers: {
"Cache-Control": "no-cache",
"Content-Type": "application/json",
},
});

// init your manager.
ConcurrencyManager(api, 1);

// const errorHandler = async (error: any) => {
// if (error?.response?.status === 401) {
// try {
// await api.get("auth/refresh");
// return api.request(error.config);
// } catch (refreshError) {}
// }
// return Promise.reject(error);
// };
// api.interceptors.response.use(
// (response) => response,
// (error) => errorHandler(error)
// );

export default api;
85 changes: 48 additions & 37 deletions frontend/code/src/Components/Chat/Services/SocketsServices.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,54 @@
import { io } from 'socket.io-client';
import { create } from 'zustand'

interface SocketStore {
socket: any;
connected: boolean;

const reconnect = () => {
return io("http://localhost:3004", {
transports: ['websocket'],
});
setSocket: () => any;
}
export const useSocketStore:any = create((set:any) => ({
socket:null,
connected:false,
setSocket : () => {

var s:any;

const soc = set((state:any) => {
if (state.socket === null){
s = io("http://localhost:3004", {
transports: ['websocket'],
'reconnection': true,
'reconnectionDelay': 1000,
'reconnectionDelayMax' : 1000,
'reconnectionAttempts': 5
});


s.on('connect_error', async() => {
await new Promise(r => setTimeout((r) => {
console.log("inside");
s = reconnect();
s.on('connect' , () => {console.log("connected")}
)
},1000))
});
return {socket:s}
}
return state
})
return soc ? soc : s;

}}))

export const useSocketStore = create<SocketStore>((set, get) => ({
socket: null,
connected: false,
setSocket: () => {
let newSocket: any = null;

set((state) => {
if (state.socket === null) {
newSocket = io("http://localhost:3004", {
transports: ['websocket'],
'reconnection': true,
'reconnectionDelay': 1000,
'reconnectionDelayMax': 1000,
'reconnectionAttempts': 5
});

// Set socket
set({ ...state, socket: newSocket });

newSocket.on('connect', () => {
console.log('Connected!');
// Set connected state
set({ ...state, connected: true });
});

newSocket.on('connect_error', async () => {
await new Promise((resolve) => setTimeout(() => {
// Set connected state
set({ ...state, connected: false });
newSocket.connect();
resolve(newSocket);
}, 1000))
});

return { ...state, socket: newSocket };
}

return state;
});

return newSocket;
}
}))

Loading

0 comments on commit 720e15c

Please sign in to comment.