Skip to content

Commit

Permalink
hook
Browse files Browse the repository at this point in the history
  • Loading branch information
NicolasHub committed Dec 30, 2024
1 parent cfee5ce commit b8fd1f3
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 37 deletions.
26 changes: 7 additions & 19 deletions backend/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import bodyParser from 'body-parser';
import sgMail from '@sendgrid/mail';
import {MongoClient} from 'mongodb';
import cors from 'cors';
import { Server } from 'socket.io';
import {Server} from 'socket.io';
import http from 'http';

import 'express-async-errors';
Expand All @@ -15,19 +15,19 @@ import appRouter from './routes';
const app = express();
const server = http.createServer(app);

// TODO nicolas finetune CORS config...
const io = new Server(server, {
// TODO nicolas finetune CORS config...
const io = new Server(server, {
cors: {
origin: "*", // Allow all origins
methods: ["GET", "POST"], // Allowed HTTP methods
allowedHeaders: ["my-custom-header", "x-socket-id"], // Optional: specify allowed headers
origin: '*', // Allow all origins
methods: ['GET', 'POST'], // Allowed HTTP methods
allowedHeaders: ['x-socket-id'], // Optional: specify allowed headers
credentials: true, // Allow credentials (e.g., cookies)
},
});

sgMail.setApiKey(appConfig.SENDGRID_API_KEY);


// TODO nicolas finetune CORS config...
// Allow only specific origins (e.g., your frontend's URL)
const corsOptions = {
origin: 'http://localhost:3000', // Replace with your frontend URL
Expand Down Expand Up @@ -103,15 +103,3 @@ server.listen(appConfig.server.port, () => {
console.log(`Server connected to port ${appConfig.server.port}, running in a ${appConfig.ENVIRONMENT} environment.`);
console.log(appConfig);
});


// TODO nicolas remove debug below...
// Handle Socket.IO connections
io.on('connection', (socket) => {
console.log('A user connected');

// Disconnect event
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
3 changes: 1 addition & 2 deletions frontend/src/actions/consultantActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import { ConsultantModel } from "../components/consultant/models/ConsultantModel
import { busyToggle, success } from "./appActions";
import { ACTION_TYPES } from "./utils/ActionTypes";
import { authService } from "../components/users/authService";
import { socketService, notifyEntityEvent } from "../components/socketio/SocketService";
import { socketService } from "../components/socketio/SocketService";
import { EntityEventPayload } from "../components/socketio/EntityEventPayload";
import { SocketEventTypes } from "../components/socketio/SocketEventTypes";
import { Dispatch } from "redux";

export function saveConsultant(
consultant: ConsultantModel,
Expand Down
6 changes: 5 additions & 1 deletion frontend/src/components/consultant/EditConsultant.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, {useState} from 'react';
import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {Container, Row, Form, Alert} from 'react-bootstrap';
import {useNavigate} from 'react-router-dom';
Expand All @@ -15,6 +15,8 @@ import {useDocumentTitle} from '../hooks/useDocumentTitle';
import {Audit} from '../admin/audit/Audit';
import {Claim} from '../users/models/UserModel';
import {useParams} from 'react-router-dom';
import { socketService } from '../socketio/SocketService';
import useEntityChangedToast from '../hooks/useEntityChangedToast';


export const EditConsultant = () => {
Expand All @@ -27,6 +29,8 @@ export const EditConsultant = () => {
.filter(x => x.email === consultant.email)
.find(x => x.slug !== params.id && x._id !== params.id));

useEntityChangedToast(model?._id);

const docTitle = consultant._id ? 'consultantEdit' : 'consultantNew';
useDocumentTitle(docTitle, {name: `${consultant.firstName} ${consultant.name}`});

Expand Down
17 changes: 17 additions & 0 deletions frontend/src/components/hooks/useEntityChangedToast.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useEffect } from "react";
import { socketService } from "../socketio/SocketService";

function useEntityChangedToast(entityId: string|null|undefined) {
useEffect(()=>{
var subs: undefined| (()=>void);

if(entityId){
subs = socketService.enableToastsForEntity(entityId);
}

return subs;

}, [entityId]);
}

export default useEntityChangedToast;
12 changes: 2 additions & 10 deletions frontend/src/components/project/EditProject.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {EnhanceWithConfirmation} from '../enhancers/EnhanceWithConfirmation';
import {Button} from '../controls/form-controls/Button';
import {isDateIntervalValid} from '../controls/other/ProjectValidator';
import { socketService } from '../socketio/SocketService';
import useEntityChangedToast from '../hooks/useEntityChangedToast';


const ConfirmationButton = EnhanceWithConfirmation(Button);
Expand All @@ -43,16 +44,7 @@ export const EditProject = () => {
const hasProjectMonths = useSelector((state: ConfacState) => state.projectsMonth.some(pm => pm.projectId === params.id));
const [needsSync, setNeedsSync] = useState<{consultant: boolean, client: boolean}>({consultant: false, client: false});

useEffect(()=>{
var subs: undefined| (()=>void);

if(model?._id){
subs = socketService.enableToastsForEntity(model?._id);
}

return subs;

}, [model?._id])
useEntityChangedToast(model?._id);

const docTitle = consultant._id ? 'projectEdit' : 'projectNew';
useDocumentTitle(docTitle, {consultant: consultant.firstName, client: client.name});
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/components/socketio/SocketService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ function createSocketService () {
}

function toastEntityChanged(eventType: SocketEventTypes, eventPayload: EntityEventPayload){
let operation = 'entityUpdated';
let operation: string | undefined;

switch(eventType){
case SocketEventTypes.EntityCreated:
operation = 'entityCreated';break;
operation = 'entityCreated'; break;
case SocketEventTypes.EntityUpdated:
operation = 'entityUpdated';break;
operation = 'entityUpdated'; break;
case SocketEventTypes.EntityDeleted:
operation = 'entityDeleted'; break;
default: throw new Error(`${eventType} not supported.`);
Expand All @@ -74,8 +74,8 @@ function createSocketService () {
);
}

function enableToastsForEntity(entityId: string){
var unsubscriptions:(()=>void)[] = [];
function enableToastsForEntity(entityId: string) {
var unsubscriptions: (()=>void)[] = [];

function registerToastForEventType(eventType: SocketEventTypes){
var process = (msg: EntityEventPayload)=>{
Expand Down

0 comments on commit b8fd1f3

Please sign in to comment.