Skip to content

Commit

Permalink
Merge pull request #34 from infinitybase/FEAT/socket-server
Browse files Browse the repository at this point in the history
Feat/socket server
  • Loading branch information
guimroque authored Nov 8, 2023
2 parents db9ddbf + 94bcb4d commit 0869c97
Show file tree
Hide file tree
Showing 5 changed files with 155 additions and 23 deletions.
30 changes: 18 additions & 12 deletions .env
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@

NODE_ENV=test

# DATABASE
DATABASE_HOST = 127.0.0.1
DATABASE_PORT = 5432
DATABASE_USERNAME = postgres
DATABASE_PASSWORD = postgres
DATABASE_NAME = postgres
DATABASE_PORT_TEST = 5432
# APP
API_PORT=3333
APP_NAME=bsafe-api
# ADMIN USER
APP_ADMIN_EMAIL=admin_user_email
APP_ADMIN_PASSWORD=admin_user_password
# TOKENS
ACCESS_TOKEN_SECRET=access_token_secret
REFRESH_TOKEN_SECRET=refresh_token_secret
# AWS
UI_URL=https://app.bsafe.pro

# App
API_PORT = 3333

# Admin user
APP_ADMIN_EMAIL = [email protected]
APP_ADMIN_PASSWORD = admin_user_password

# Tokens
ACCESS_TOKEN_SECRET = access_token_secret
REFRESH_TOKEN_SECRET = refresh_token_secret
# Time should be in minutes
TOKEN_EXPIRATION_TIME = 15
#UI_URL=http://localhost:5173
UI_URL=https://app.bsafe.pro

27 changes: 21 additions & 6 deletions docker/database/.env.dev
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
DATABASE_HOST=127.0.0.1
DATABASE_PORT=5432
DATABASE_USERNAME=postgres
DATABASE_PASSWORD=postgres
DATABASE_NAME=postgres
NODE_ENV=development
# Database
DATABASE_HOST = 127.0.0.1
DATABASE_PORT = 5432
DATABASE_USERNAME = postgres
DATABASE_PASSWORD = postgres
DATABASE_NAME = postgres

# App
API_PORT = 3333

# Admin user
APP_ADMIN_EMAIL = [email protected]
APP_ADMIN_PASSWORD = admin_user_password

# Tokens
ACCESS_TOKEN_SECRET = access_token_secret
REFRESH_TOKEN_SECRET = refresh_token_secret
# Time should be in minutes
TOKEN_EXPIRATION_TIME = 15
UI_URL=http://localhost:5173
# UI_URL=https://app.bsafe.pro
6 changes: 3 additions & 3 deletions src/mocks/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export const netoworks: { [key: string]: string } = {
local: 'http://127.0.0.1:4000/graphql',
};

export const providers: { [key: string]: Provider } = {
beta4: new Provider(netoworks['beta4']),
local: new Provider(netoworks['local']),
export const providers: { [key: string]: () => Promise<Provider> } = {
beta4: async () => await Provider.create(netoworks['beta4']),
local: async () => await Provider.create(netoworks['local']),
};
13 changes: 11 additions & 2 deletions src/server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@ import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import Express from 'express';
import http from 'http';
import morgan from 'morgan';
import { Socket } from 'socket.io';

import { router } from '@src/routes';

import { handleErrors } from '@middlewares/index';

import SocketIOServer from './socket';

const { API_PORT, PORT } = process.env;

class App {
private readonly app: Express.Application;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
httpServer!: any;
constructor() {
this.app = Express();

this.initMiddlewares();
this.initRoutes();
this.initErrorHandler();
Expand All @@ -24,9 +30,12 @@ class App {
// App
const port = API_PORT || PORT || 3333;
console.log('[APP] Starting application.');
this.app.listen(port, () => {
this.httpServer = http.createServer(this.app);
this.httpServer.listen(port, () => {
console.log(`[APP] Application running in http://localhost:${port}`);
});

new SocketIOServer(this.httpServer);
}

private initMiddlewares() {
Expand Down
102 changes: 102 additions & 0 deletions src/server/socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { Server, ServerOptions } from 'socket.io';

export interface ISocketUser {
userID: string;
username: string;
}

export enum SocketChannels {
WALLET = '[WALLET]',
POPUP_AUTH = '[POPUP_AUTH]',
POPUP_TRANSFER = '[POPUP_TRANSFER]',
}

export interface ISocketEvent {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
content: any; // todo: typing all events, and useing or
to: string;
}

class SocketIOServer extends Server {
//todo: upgrade this type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private io: any;

constructor(httpServer: Express.Application, options?: Partial<ServerOptions>) {
super(httpServer);

// eslint-disable-next-line @typescript-eslint/no-var-requires
this.io = new Server(httpServer, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
...options,
});

//middleware de conexao
this.io.use((socket, next) => {
const username = socket.handshake.auth.username;
const hasValidEvent =
username.includes(SocketChannels.WALLET) ||
username.includes(SocketChannels.POPUP_AUTH) ||
username.includes(SocketChannels.POPUP_TRANSFER);
if (!username || !hasValidEvent) {
return next(new Error('invalid username'));
}

console.log('[user_connectted]:', username);
socket.username = username;
next();
});

this.io.on('connection', socket => {
//[to list all users]
// const users: ISocketUser[] = [];
// for (const [id, socket] of this.io.of('/').sockets) {
// users.push({ userID: id, username: socket.username });
// }

/*
[WALLET]
- complement this connection depends to event content
- for exemple, complement payload to message to send to client
*/
socket.on('[WALLET]', ({ content, to }: ISocketEvent) => {
console.log('[WALLET]');
socket.to(to).emit('[WALLET]', {
content,
from: socket.id,
});
});

/*
[POPUP_TRANSFER]
- complement this connection depends to event content
- for exemple, complement payload to message to send to client
*/
socket.on('[POPUP_TRANSFER]', ({ content, to }: ISocketEvent) => {
console.log('[POPUP_TRANSFER]');
socket.to(to).emit('[POPUP_TRANSFER]', {
content,
from: socket.id,
});
});

/*
[POPUP_AUTH]
- complement this connection depends to event content
- for exemple, complement payload to message to send to client
*/
socket.on('[POPUP_AUTH]', ({ content, to }: ISocketEvent) => {
console.log('[POPUP_AUTH]');
socket.to(to).emit('[POPUP_AUTH]', {
content,
from: socket.id,
});
});
});
}
}

export default SocketIOServer;

0 comments on commit 0869c97

Please sign in to comment.