From 896f80d59f609e4db7f7404f0899a98a05d72a77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Mon, 10 Jul 2017 09:03:18 +0200 Subject: [PATCH] Start refactoring sockets example --- examples/with-sockets/io/index.js | 24 ++++++++++++++++++++++ examples/with-sockets/nuxt.config.js | 6 ++---- examples/with-sockets/pages/index.vue | 2 +- examples/with-sockets/plugins/socket.io.js | 2 +- 4 files changed, 28 insertions(+), 6 deletions(-) create mode 100644 examples/with-sockets/io/index.js diff --git a/examples/with-sockets/io/index.js b/examples/with-sockets/io/index.js new file mode 100644 index 0000000000..95e55fcf91 --- /dev/null +++ b/examples/with-sockets/io/index.js @@ -0,0 +1,24 @@ +module.exports = function () { + const server = require('http').createServer(this.nuxt.renderer.app) + const io = require('socket.io')(server) + + // overwrite nuxt.listen() + this.nuxt.listen = (port, host) => new Promise((resolve) => server.listen(port || 3000, host || 'localhost', resolve)) + // close this server on 'close' event + this.nuxt.plugin('close', () => new Promise((resolve) => server.close(resolve))) + + // Add `socket.io-client` in vendor + this.addVendor('socket.io-client') + + // Add socket.io events + let messages = [] + io.on('connection', (socket) => { + socket.on('last-messages', function (fn) { + fn(messages.slice(-50)) + }); + socket.on('send-message', function (message) { + messages.push(message) + socket.broadcast.emit('new-message', message) + }) + }); +} \ No newline at end of file diff --git a/examples/with-sockets/nuxt.config.js b/examples/with-sockets/nuxt.config.js index 7ca9c60b1f..34e2ec30a1 100644 --- a/examples/with-sockets/nuxt.config.js +++ b/examples/with-sockets/nuxt.config.js @@ -1,14 +1,12 @@ module.exports = { - build: { - vendor: ['socket.io-client'] - }, head: { meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' } ] }, + modules: ['~/io'], env: { - HOST_URL: process.env.HOST_URL || 'http://localhost:3000' + WS_URL: process.env.WS_URL || 'http://localhost:3000' } } diff --git a/examples/with-sockets/pages/index.vue b/examples/with-sockets/pages/index.vue index 4e4f66c714..1e2fb24700 100644 --- a/examples/with-sockets/pages/index.vue +++ b/examples/with-sockets/pages/index.vue @@ -14,7 +14,7 @@