Skip to content
This repository has been archived by the owner on Nov 10, 2022. It is now read-only.

Commit

Permalink
refactor: add event class and separate socket.io server
Browse files Browse the repository at this point in the history
  • Loading branch information
severo committed Jan 20, 2020
1 parent 6fdf3a2 commit 97d51d2
Show file tree
Hide file tree
Showing 9 changed files with 130 additions and 74 deletions.
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@types/express": "^4.17.2",
"@types/mocha": "^5.2.7",
"@types/node": "^13.1.8",
"@types/socket.io": "^2.1.4",
"@types/socket.io-client": "^1.4.32",
"chai": "^4.2.0",
"concurrently": "^5.0.2",
Expand Down
10 changes: 10 additions & 0 deletions src/domain/events/connection.event.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { expect } from 'chai'
import { ConnectionEvent } from './connection.event'

describe('Events', () => {
describe('ConnectionEvent', () => {
it("should have 'connection' event as name", () => {
expect(ConnectionEvent.eventName).to.equal('connection')
})
})
})
5 changes: 5 additions & 0 deletions src/domain/events/connection.event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Event } from './event'

export class ConnectionEvent {
static readonly eventName: string = Event.Connection
}
3 changes: 3 additions & 0 deletions src/domain/events/event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export class Event {
static readonly Connection = 'connection'
}
1 change: 1 addition & 0 deletions src/domain/events/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './connection.event'
94 changes: 48 additions & 46 deletions src/server.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ioc from 'socket.io-client'
import { expect } from 'chai'
import { http, io } from './server'
import { server, socketServer } from './server'

process.env.NODE_ENV = 'test'

Expand All @@ -10,48 +10,50 @@ const ioOptions = {
reconnection: false,
}

describe('/occupapp-beta', function() {
let clientSocket: SocketIOClient.Socket
let socketIds: SocketIOClient.Socket['id'][]

beforeEach(async function() {
http.listen('3001')
clientSocket = ioc('http://localhost:3001/', ioOptions)
socketIds = await Promise.all([
new Promise(resolve => {
clientSocket.on('connect', () => {
resolve(clientSocket.id)
})
}),
new Promise(resolve => {
io.on('connection', (socket: SocketIOClient.Socket) => {
resolve(socket.id)
})
}),
])
})
afterEach(function(done) {
clientSocket.disconnect()
http.close()

done()
})

it('should use the same socket id clientside and serverside', function() {
return expect(socketIds[0]).to.equal(socketIds[1])
})

// it('should update the user profile on "update-profile" event', function() {
// const name = 'test'
// const color = '#888888'
// clientSocket.emit('update-profile', { name, color }, result => {
// expect(result).to.have.property('status')
// expect(result.status).to.equal('success')
// expect(result).to.have.property('data')
// expect(result.data).to.have.property('name')
// expect(result.data.name).to.equal(name)
// expect(result.data).to.have.property('color')
// expect(result.data.color).to.equal(color)
// })
// })
})
// describe('/occupapp-beta', function() {
// let clientSocket: SocketIOClient.Socket
// let socketIds: SocketIOClient.Socket['id'][]
//
// beforeEach(async function() {
// socketServer.connect()
// server.listen('3001')
// clientSocket = ioc('http://localhost:3001/', ioOptions)
// socketIds = await Promise.all([
// new Promise(resolve => {
// clientSocket.on('connect', () => {
// resolve(clientSocket.id)
// })
// }),
// new Promise(resolve => {
// io.on('connection', (socket: SocketIOClient.Socket) => {
// resolve(socket.id)
// })
// }),
// ])
// })
// afterEach(function(done) {
// clientSocket.disconnect()
// server.close()
//
// done()
// })
//
// it('should use the same socket id clientside and serverside', function() {
// return expect(socketIds[0]).to.equal(socketIds[1])
// })
//
// it('should update the user profile on "update-profile" event', function() {
// // TODO: DOES NOT WORK AT ALL!!! NEVER EXECUTED
// const name = 'test'
// const color = '#888888'
// clientSocket.emit('update-profile', { name, color }, (result: any) => {
// expect(result).to.have.property('status')
// expect(result.status).to.equal('success')
// expect(result).to.have.property('data')
// expect(result.data).to.have.property('name')
// expect(result.data.name).to.equal(name)
// expect(result.data).to.have.property('color')
// expect(result.data.color).to.equal(color)
// })
// })
// })
43 changes: 15 additions & 28 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { default as express } from 'express'
const app = express()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const port = process.env.PORT || 3000
import http from 'http'
import express from 'express'
import socketIo from 'socket.io'
import { Socket } from './socket.io/socket'

// const { RateLimiterMemory } = require('rate-limiter-flexible')

//
Expand Down Expand Up @@ -79,7 +79,7 @@ const port = process.env.PORT || 3000
// io.of('/occupapp-beta').to(room.name).emit('list-profiles', room.profiles)
// }
//
// const updateProfile = (socketId, profile, ack) => {
// const updateProfile = (socketId: SocketIOClient.Socket['id'], profile, ack) => {
// // Validate payload
// const checkedProfile = UserProfile.checkProfile(profile)
// if (checkedProfile.error !== undefined) {
Expand All @@ -102,30 +102,17 @@ const port = process.env.PORT || 3000
// ack({ status: 'success', data: currentUser.profile })
// }
// }
//
io.of('/occupapp-beta').on('connection', (socket: SocketIOClient.Socket) => {
// socket.on('update-profile', (profile, ack) => updateProfile(socket.id, profile, ack))
// rooms (unique room)
// socket.on('join', (userProfile, ack) => {
// if (socket.rooms.includes(uniqueRoom)) {
// ack({'status': 'error', 'reason': "Already in the room 'default room'"})
// }
// socket.join(uniqueRoom, () => {
// // Add or update the guest in the list of
// addGuest(socket, guestData, ack))
//
// let rooms = Object.keys(socket.rooms);
// console.log(rooms); // [ <socket.id>, 'room 237' ]
// io.to('room 237').emit('a new user has joined the room'); // broadcast to everyone in the room
// });
// }
// // socket.on('update-urlqueryspec', onUpdateUrlQuerySpec(socket))
// socket.on('disconnecting', () => removeGuest(socket))
})

const port: number = +process.env.PORT || 3000
const app: express.Application = express()
const server = http.createServer(<any>app)
const io = socketIo(server)
const socketServer = new Socket(io)

if (require.main === module) {
http.listen(port, () => console.log('listening on port ' + port))
socketServer.connect()
server.listen(port)
}

// export the server so it can be easily called for testing
export { http, io }
export { server, socketServer }
38 changes: 38 additions & 0 deletions src/socket.io/socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { ConnectionEvent } from '../domain/events'

class Socket {
private io: SocketIO.Server
constructor(io: SocketIO.Server) {
this.io = io
}

public connect() {
this.io
.of('/occupapp-beta')
.on(ConnectionEvent.eventName, (socket: SocketIOClient.Socket) => {
// socket.on(
// 'update-profile',
// () => console.log('ok')
// //updateProfile(socket.id, profile, ack)
// )
// rooms (unique room)
// socket.on('join', (userProfile, ack) => {
// if (socket.rooms.includes(uniqueRoom)) {
// ack({'status': 'error', 'reason': "Already in the room 'default room'"})
// }
// socket.join(uniqueRoom, () => {
// // Add or update the guest in the list of
// addGuest(socket, guestData, ack))
//
// let rooms = Object.keys(socket.rooms);
// console.log(rooms); // [ <socket.id>, 'room 237' ]
// io.to('room 237').emit('a new user has joined the room'); // broadcast to everyone in the room
// });
// }
// // socket.on('update-urlqueryspec', onUpdateUrlQuerySpec(socket))
// socket.on('disconnecting', () => removeGuest(socket))
})
}
}

export { Socket }

0 comments on commit 97d51d2

Please sign in to comment.