GithubHelp home page GithubHelp logo

jpillora / velox Goto Github PK

View Code? Open in Web Editor NEW
176.0 8.0 15.0 1.27 MB

Real-time Go struct to JS object synchronisation over SSE and WebSockets

License: MIT License

Go 58.96% JavaScript 40.06% HTML 0.98%

velox's Introduction

velox

GoDoc

Real-time JS object synchronisation over SSE and WebSockets in Go and JavaScript (Node.js and browser)

Features

Quick Usage

Server (Go)

//syncable struct
type Foo struct {
	velox.State
	A, B int
}
foo := &Foo{}
//serve velox.js client library (assets/dist/velox.min.js)
http.Handle("/velox.js", velox.JS)
//serve velox sync endpoint for foo
http.Handle("/sync", velox.SyncHandler(foo))
//make changes
foo.A = 42
foo.B = 21
//push to client
foo.Push()

Server (Node)

//syncable object
let foo = {
  a: 1,
  b: 2
};
//express server
let app = express();
//serve velox.js client library (assets/dist/velox.min.js)
app.get("/velox.js", velox.JS);
//serve velox sync endpoint for foo (adds $push method)
app.get("/sync", velox.handle(foo));
//make changes
foo.a = 42;
foo.b = 21;
//push to client
foo.$push();

Client (Node and Browser)

// load script /velox.js
var foo = {};
var v = velox("/sync", foo);
v.onupdate = function() {
  //foo.A === 42 and foo.B === 21
};

API

Server API (Go)

GoDoc

Server API (Node)

  • velox.handle(object) function returns v - Creates a new route handler for use with express
  • velox.state(object) function returns state - Creates or restores a velox state from a given object
  • state.handle(req, res) function returns Promise - Handle the provided express request/response. Resolves on connection close. Rejects on any error.

Client API (Node and Browser)

  • velox(url, object) function returns v - Creates a new SSE velox connection
  • velox.sse(url, object) function returns v - Creates a new SSE velox connection
  • velox.ws(url, object) function returns v - Creates a new WS velox connection
  • v.onupdate(object) function - Called when a server push is received
  • v.onerror(err) function - Called when a connection error occurs
  • v.onconnect() function - Called when the connection is opened
  • v.ondisconnect() function - Called when the connection is closed
  • v.onchange(bool) function - Called when the connection is opened or closed
  • v.connected bool - Denotes whether the connection is currently open
  • v.ws bool - Denotes whether the connection is in web sockets mode
  • v.sse bool - Denotes whether the connection is in server-sent events mode

Example

See this simple example/ and view it live here: https://velox.jpillora.com

screenshot

Here is a screenshot from this example page, showing the messages arriving as either a full replacement of the object or just a delta. The server will send which ever is smaller.

Notes

  • JS object properties beginning with $ will be ignored to play nice with Angular.

  • JS object with an $apply function will automatically be called on each update to play nice with Angular.

  • velox.SyncHandler is just a small wrapper around velox.Sync:

    	```go
    	func SyncHandler(gostruct interface{}) http.Handler {
    		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    			if conn, err := Sync(gostruct, w, r); err == nil {
    				conn.Wait()
    			}
    		})
    	}
    	```
    

Known issues

  • Object synchronization is currently one way (server to client) only.
  • Object diff has not been optimized. It is a simple property-by-property comparison.

TODO

  • WebRTC support
  • Plain http server support in Node
  • WebSockets support in Node

MIT License

Copyright © 2018 Jaime Pillora <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

velox's People

Contributors

jpillora avatar dependabot[bot] avatar sgohl avatar boypt avatar

Stargazers

 avatar Hana Mohan avatar Alexey Aksenov avatar  avatar abc avatar Lucas Menicucci avatar  avatar eagle avatar Nikita Zhenev avatar Marco Pantaleoni avatar Darshan avatar Hristo Karchokov avatar Andrei Surugiu avatar Can Evgin avatar Nikita Nikonov avatar James Yang avatar Roman avatar creatint avatar Frank avatar Choquet Nicolas avatar GAURAV avatar LiKun avatar Alex avatar kolisn avatar A.Kadir Mutlu avatar  avatar Herman Slatman avatar gleeco avatar Maxim Shek avatar J-D avatar Rob Gering avatar  avatar kyle avatar ik5 avatar Liut avatar Giovanni Delgado avatar Valar avatar  avatar Johnny avatar  avatar Waleed AlMalki avatar Happy bull avatar 尹名洋 avatar Nate Woods avatar levon avatar Ivan Alexandrov avatar vulcangz avatar Anders Storhaug avatar Michael Branch avatar Rasmus Lindroth avatar George Opritescu avatar wyrover avatar Theofanis Despoudis avatar Berkant İpek avatar Thiago Zilli Sarmento avatar ypcpy avatar  avatar Sebastian Macias avatar Kevin Segal avatar Gleb avatar Abdul Hameed avatar Dhananjay verma avatar  avatar Steffen Uhlig avatar Thinh Nguyen avatar tom.wen avatar Maurizio Del Corno avatar Eduardo Oliveira avatar  avatar merik avatar  avatar  avatar  avatar Ramón Berrutti avatar Charle Demers avatar Dmitry Chusovitin avatar Nicolas Marshall avatar Zy avatar Michael S. Manley avatar Vsevolod Balashov avatar Nanxi avatar  avatar  avatar Kevin Darlington avatar  avatar Jesse White avatar  avatar Miki Oracle avatar Serge Simard avatar Larry Clapp avatar jow blew avatar Lubomir Anastasov avatar The Brain avatar Robert McNeil avatar Michael Hood avatar robbin han avatar Dobrosław Żybort avatar ᴀɴᴛᴏɴ ɴᴏᴠᴏᴊɪʟᴏᴠ avatar David Smith avatar Astra Rehbein avatar

Watchers

Sebastian Macias avatar  avatar James Cloos avatar Think-Free avatar Kirill Fries-Raevskiy avatar Choquet Nicolas avatar  avatar  avatar

velox's Issues

Allow object to be empty on client side

Hey there,

I came across your project and I really love it!

I recently realized that the Velox constructor on the client side doesn't allow for the obj parameter to be empty. Your examples use global objects like

// load script /velox.js
var foo = {};
var v = velox("/sync", foo);
v.onupdate = function() {
  //foo.A === 42 and foo.B === 21
};

As it can be seen, there are no requirements to the passed object besides being of type object.

However, since the onupdate callback passes this.obj as a parameter anyway, the object containing the received data doesn't need to be global (when using SSE, at least). Right now I'm using

var v = velox("/sync", {});
v.onupdate = function(obj) {
  //obj.A === 42 and obj.B === 21
};

to avoid using global objects, but this still looks a bit ugly. It would be better if the empty object could be omitted and instead be implicitly created by the constructor like velox("/sync").

I would therefore propose a change in the constructor of the Velox class like

obj = obj || {};
if (typeof obj !== "object") {
  throw "Invalid object";
}
this.obj = obj;

to implicitly create an empty object when the parameter obj is omitted instead of throwing an error.

Kindly
bliepp

caching

The way that the data is held on the golang side is a pointer ?
So its a shared memory area, and so i was condering about using it as a cache, because it seems to make sense.
As such, i am thinking that some sort of management channel is needed, so that i can tell clients to drop their cache and reload. The reason i am thinking this is worthwhile is because the cache needs to be dropped and reloaded when upgrades happen etc. Otherwise there is a risk that the clients will think that all data has been dropped and react in inappropriate ways.

i could be wrong here of course, but as i was thinking through use cases of using this on a project, its what hit me.

What do you think ?

thanksn advance.

How to define a custom event type?

As shown in this screenshot:

Screenshot

All the events are being sent with type "message". Is there a way to change for instance to "chat", "price", "my-type"?

Thanks

Feature: Implement a Go client

This is great.

The patch functionality being used server to server and server to web client is reusable

I have 2 ideas :

  1. As the data changes on the client, you want to be able to react to it. This is an interesting challenge. I am thinking a simple switch statement, almost like a reverse router. The programmer simply expressed changes in the strut they subscribe to.
  2. East West agnostic. Using this just client server is awesome. But I can see it being useful between golang servers too.

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.