Skip to content

Commit

Permalink
Merge pull request #8 from internxt/refactor/receive-user-id-or-email
Browse files Browse the repository at this point in the history
[_]: refactor(handler): receive userId or email
  • Loading branch information
fabioespinosa authored Aug 10, 2022
2 parents 4a03ffa + 5c7195d commit 14181fe
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
12 changes: 9 additions & 3 deletions src/auth-socket-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,16 @@ export default function registerAuthSocketMiddleware(io: Server) {
next(new Error());
}
logger.info(`Token decoded: ${decoded}`);
const email = typeof decoded === 'string' ? decoded : decoded!.email;

logger.info(`${email} is listening notifications`);
socket.join(email);
if (decoded && typeof decoded !== 'string' && decoded.userId) {
logger.info(`userId: ${decoded.userId} is listening notifications`);
socket.join(decoded.userId);
} else {
const email = typeof decoded === 'string' ? decoded : decoded!.email;
logger.info(`email: ${email} is listening notifications`);
socket.join(email);
}

next();
});
});
Expand Down
14 changes: 11 additions & 3 deletions src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import Logger from './logger';
type RequestBody = {
event: string;
payload: any;
email: string;
email?: string;
userId?: string;
clientId?: string;
};

function validateBody(body: Record<string, any>): RequestBody {
if (body.event && body.payload && body.email) return body as RequestBody;
if (body.event && body.payload && (body.email || body.userId)) return body as RequestBody;
throw new Error('Body is not in the expected format');
}

Expand All @@ -28,7 +29,14 @@ export default function registerHandler(app: Express, io: Server) {

logger.info(`Event is going to be emited: ${JSON.stringify(body, null, 2)}`);

io.to(body.email).emit('event', body);
if(body.email){
io.to(body.email).emit('event', body);
}

if(body.userId){
io.to(body.userId).emit('event', body);
}

res.status(201).send();
});
}

0 comments on commit 14181fe

Please sign in to comment.