基于WebSockets實現REST API的庫:restSocket

jopen 10年前發布 | 21K 次閱讀 網絡工具包 restSocket

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.baiduhome.net/lib/view/home/1416559663977

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!