基于WebSockets实现REST API的库:restSocket

jopen 10年前

restSocket 是一个微型库,能够实现:

  • 允许客户端充当基于WebSockets的服务器REST API,。
  • 让客户端通过WebSockets轮询服务器就像一个REST API。

restSocket 需要 LoDash 或 Underscore (tested with LoDash 2.4.1).

用法

Just drop it on the page like so:

<script src="restSocket.min.js"></script>

Then initiate a restSocket like so:

var todoSocket = new restSocket({      path: 'localhost:8080/todo', // this is the only required part of this settings object      authToken: function(){          // logic to get an authToken          // this function can be replaced with a simple string          return '455B1D51-CC4C-40C1-BEFB-579CD18D905B';      },      stringifyPayloadToServer: true, // defaults to false      success: function(){          // stuff to do after connection is authorized      },      error: function(){          // if an error occurs      },      onclose: function(event){          // stuff to do if/when connection is closed          // example: you can just try to reopen the connection (it will only do this once every 2 seconds)          todoSocket.reopen();      },      api: {          '/todos': {              'PATCH': {                  success: function(payload){                      // you may explicitly define what to do on success and error...                  },                  error: function(err){                      // do stuff if an error happens                  }              },              'POST': function(payload){                  // ...or you can just give it one function, which will be called on success only              }          },          '/todos/:id': {              'PUT': {                  success: function(payload, args){                      // args will be a single-property object with key 'id' and a value based on the resource the server is requesting                  },                  error: function(err){                      // err will be a normal WebSockets error object                      return;                  }              }          }      }  });

Then make requests to the server like so:

todoSocket.get('todos');    // you can also specify params for the GET method  todoSocket.get('todos', {filter: 'doneOnly'});    todoSocket.patch('todos/2', {done: true});    todoSocket.post('todos', {description: 'This thing', done: false});    todoSocket.put('todos/1', {id: 2, description: 'Something else', done: false})    // remove initiates a DELETE request  todoSocket.remove('todos/1');

项目主页:http://www.open-open.com/lib/view/home/1416559663977