Git Product home page Git Product logo

vuex-socketio-plugin's Introduction

vuex-socketio-plugin

Vuex plugin to integrate socket.io client

Install

npm install vuex-socketio-plugin --save

Simple Example

store.ts

import Vuex, { Store } from 'vuex'
import Vue from 'vue'
import { createSocketioPlugin } from 'vuex-socketio-plugin'
import * as io from 'socket.io-client'

Vue.use(Vuex)

let _client: (typeof io.Socket) | null = null;
export type State = { messages: string[] }
const store = new Vuex.Store<State>({
  plugins: [createSocketioPlugin('http://localhost:3000')],
  state: {
    messages: []
  },
  mutations: {
    SOCKET_CONNECT(state, { client }) {
      console.log('connected')
      _client = client;
    },
    SOCKET_CHAT_MESSAGE(state, { data }) {
      state.messages = state.messages.concat([data[0]])
    }
  },
  actions: {
    postMessage(context, payload: { message: string }) {
      if (!_client) {
        throw new Error("don't have connection")
      }
      _client.emit('CHAT_MESSAGE', payload.message)
    }
  }
})

export default store

Usage

createSocketioPlugin

Creates a new instance of the plugin. You can give an URL string or custom socket.io-client instance.

createSocketioPlugin('http://localhost:3000') // apply default as socket-io(auto-connect)
createSocketioPlugin(io('http://localhost:3000', { autoConnect: false }) // if you want to customize you can give any socket.io instance

If you want to use multi connection, you can give an array of it.

createSocketioPlugin([
  'http://localhost:3000/function1',
  'http://localhost:3000/function2',
  'http://localhost:3000/function3'
])

Prefix are set automatically to each Mutation and Action.(See Mutation And Action) If you want to change prefix name, you can give it as actionPrefix and mutationPrefix options.

createSocketioPlugin([
  'http://localhost:3000/function1',
  'http://localhost:3000/function2',
  'http://localhost:3000/function3'
], {
  actionPrefix: 'socket/soc_',
  mutationPrefix: 'socket/SOC_'
})

Mutation and Action

When it receives any SocketIO events, vuex-socketio-plugin triggers Mutation and Action. SOCKET_ prefix is added on MutationName, prefix socket_ is added on ActionName . (MutationName and ActionName consists from prefix + EventName.)

  mutations: {
    SOCKET_CONNECT(state, payload) {
      console.log('connected on mutation')
    },
  },
  actions: {
    socket_connect(context, payload) {
      console.log('connected on action')
    }
  }

Note: In case of mutation, default socket.io events are UpperCase. Pleae ref socket.io docs about type of default events.

Both of mutation and action payload includes client and data parameters. client is socket.io instance. You can emit any event via this. data is received message. It is always array type.

Socket.io Namespaces and Vuex Namespaced Modules

Socket.io namespaces is mapped Vuex namespaced Modules.

If you use socket.io namespaces, you can receive which one of below types.

{
  plugins: [
    createSocketioPlugin('http://localhost:3000/bar')
  ],
  mutations: {
    SOCKET_CONNECT: { ... } // default
    SOCKET_bar_CONNECT: { ... } // prefix + namespace + event name
  },
  modules: {
    bar: {
      SOCKET_CONNECT: { ... } // namespaced module + prefix + event name
    }
  }
}

Because this is a convention you don't have to set any configtation. It is triggered to be found mutation and action at first.

getClients

If you want to get a socket.io client, you can use getClients .

Example

import { getClients } from 'vuex-socketio-plugin'
getClients().forEach(v => v.connect())

Example

example

vuex-socketio-plugin's People

Contributors

joe-re avatar ktsn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vuex-socketio-plugin's Issues

not connect, pls help

Hi, I'm little bit modified your example, I cant obtaine a connection between client and server, pls take look:
store/index.ts
import Vue from 'vue'
import Vuex, { ActionTree, MutationTree } from 'vuex'
import { socket1 } from './socket1';
import { socket2 } from './socket2';
import { createSocketioPlugin } from 'vuex-socketio-plugin'
import * as io from 'socket.io-client'

Vue.use(Vuex)

const path1 = '/socket1',
path2 = '/socket2';
export const store = new Vuex.Store({
plugins: [
createSocketioPlugin(io('http://localhost:8888', { path: path1 })),
createSocketioPlugin(io('http://localhost:8888', { path: path2 }))
],
state: {},
mutations: {
},
modules: {
socket1,
socket2
},
})
store/socket1.ts; socket2.ts the similar
import { Store, GetterTree, MutationTree, ActionTree, Module } from 'vuex'
import { RootState, SocketState } from '../types'

const state: SocketState = {
isLogged: false,
error: '',
messages: [],
_client: null
}
const getters: GetterTree<SocketState, RootState> = {
messages: state => state.messages
}
const mutations: MutationTree = {
SOCKET_CONNECT(state, { client }) {
state.isLogged = true
state._client = client
},
SOCKET_COUNTER(state, { data }){
state.messages = state.messages.concat([data[0]])
},
}
export const socket1: Module<SocketState, RootState> = {
state,
getters,
mutations,
namespaced: true
}

types.ts
import * as io from 'socket.io-client'

export interface RootState{
socket1: SocketState
}
export interface SocketState {
isLogged: boolean
error: string
messages: Message[],
_client: (typeof io.Socket) | null
}
export interface Message {
message: string
}
server.ts
import * as http from 'http';
import * as socketIo from 'socket.io';
// import { handler } from './handler';
import { SioEvent, SioController, SioNamespace } from '../lib/';
const allowedOrigins = 'http://localhost:8080';
// const app = http.createServer(handler);
const app = http.createServer(function (req, res) {
res.writeHead(200, {'Access-Control-Allow-Origin' : allowedOrigins,
'Access-Control-Allow-Credentials' : 'true',
'Access-Control-Allow-Headers': ['Content-Type', 'Authorization'],
'Content-Type': 'text/plain'});
res.end();
});

const io = socketIo(app);
app.listen(8888);

@SioNamespace({
name: '/socket1',
onConnection: [TestIo.onConnection]
})
class TestIo {
private counter = 1;

static onConnection(socket) {
socket.emit('COUNTER', {
counter: 'Start counting!'
});
}

@SioEvent()
testMethod(data: any, socket: SocketIO.Socket) {
console.log(data);
setTimeout(() => {
socket.emit('COUNTER', {
counter: this.counter
});
this.counter += 1;
}, 1000);
}
}

@SioNamespace({
name: '/socket2',
onConnection: [TestIo2.onConnection]
})
class TestIo2 {
private counter = 1;

static onConnection(socket) {
socket.emit('COUNTER2', {
counter: 'Start counting!'
});
}

@SioEvent()
testMethod2(data, socket: SocketIO.Socket) {
console.log(data);
setTimeout(() => {
socket.emit('COUNTER2', {
counter: this.counter
});
this.counter += 1;
}, 1000);
}
}

const sioCtrl = SioController.getInstance();
sioCtrl.init(io);
and screenshot attached with devtools and Helloworld.vue
2018-05-10 19-13-37
I dont need to bind server.ts to index.html in case I should develop docker swarm mult-host network with NGINX and I shoud separate server.ts. At present moment it's initial step for better understanding with CORS ...
So, I'm kindly ask U to provide some advise. Thank U

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.