Last active
April 18, 2019 09:23
-
-
Save maruware/d303e6c3f1c5822f4efe78a90ace609a to your computer and use it in GitHub Desktop.
koa + socket.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BaseContext } from 'koa' | |
declare module 'koa' { | |
interface BaseContext { | |
io: SocketIO.Server | |
} | |
} | |
export default (io: SocketIO.Server) => async ( | |
ctx: BaseContext, | |
next: () => Promise<any> | |
) => { | |
ctx.io = io | |
await next() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import http from 'http' | |
import Koa from 'koa' | |
import bodyParser from 'koa-bodyparser' | |
import socketIo from 'socket.io' | |
import koaSocket from './middlewares/koa-socketio' | |
import setupSocket from './setupSocket' | |
const app = new Koa() | |
app.use(bodyParser()) | |
app.use(koaError()) | |
const server = http.createServer(app.callback()) | |
const io = socketIo.listen(server) | |
app.use(koaSocket(io)) | |
setupSocket(io) | |
export default server |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socketIo from 'socket.io' | |
export default (io: socketIo.Server) => { | |
io.on('connection', socket => { | |
socket.on('some_event', (data: any) => { | |
console.log('some_event', data) | |
}) | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-env jest */ | |
import request from 'supertest' | |
import io from 'socket.io-client' | |
import server from '../../src/server' | |
server.listen(9999) | |
const socket = io.connect('http://localhost:9999', { | |
transports: ['websocket'] | |
}) | |
describe('api socket test', () => { | |
afterAll(async () => { | |
socket.disconnect() | |
server.close() | |
}) | |
it('example', async () => { | |
const data = {sample: 'test'} | |
let mockCallback = jest.fn() | |
socket.once('some_event', mockCallback) | |
res = await request(server) | |
.post('/api/some') | |
.send(data) | |
expect(res.status).toBe(200) | |
expect(mockCallback.mock.calls.length).toBe(1) | |
expect(mockCallback.mock.calls[0][0]).toEqual(data) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment