Skip to content

Instantly share code, notes, and snippets.

@shellscape
Last active December 11, 2018 15:13
Show Gist options
  • Save shellscape/2020916f92be5d61f4d411fb6d2bce61 to your computer and use it in GitHub Desktop.
Save shellscape/2020916f92be5d61f4d411fb6d2bce61 to your computer and use it in GitHub Desktop.
const defer = require('p-defer');
const getPort = require('get-port');
const Koa = require('koa');
const router = require('koa-route');
const WebSocket = require('ws');
const socketServer = new WebSocket.Server({ noServer: true });
/* eslint-disable no-param-reassign */
const middleware = async (ctx, next) => {
const deferred = defer();
const { upgrade = '' } = ctx.request.headers;
const upgradable = upgrade
.split(',')
.map((header) => header.trim())
.includes('websocket');
if (upgradable) {
ctx.ws = async () => {
socketServer.handleUpgrade(ctx.req, ctx.request.socket, Buffer.alloc(0), deferred.resolve);
ctx.respond = false;
return deferred.promise;
};
}
await next();
};
const run = async (t) => {
const app = new Koa();
const port = await getPort();
const uri = `ws://localhost:${port}/test`;
const routeDeferred = defer();
const resultDeferred = defer();
app.use(middleware);
app.use(
router.get('/test', async (ctx) => {
const socket = await ctx.ws();
routeDeferred.resolve();
})
);
const server = app.listen(port);
await {
then(r, f) {
server.on('listening', r);
server.on('error', f);
}
};
const socket = new WebSocket(uri);
socket.on('open', async () => {
await routeDeferred.promise;
socket.close();
resultDeferred.resolve();
});
await resultDeferred.promise;
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment