$sailsSocket
service in module ngsails

Description

The $sailsSocket service is the core service that facilitates communication with sails via socket.io

The $sailsSocket API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

General usage

The $sailsSocket service is a function which takes a single argument — a configuration object — that is used to generate a request and returns a promise with two $sailsSocket specific methods: success and error.

  $sailsSocket({method: 'GET', url: '/someUrl'}).
    success(function(data, status, headers, config) {
      // this callback will be called asynchronously
      // when the response is available
    }).
    error(function(data, status, headers, config) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });

Since the returned value of calling the $sailsSocket function is a promise, you can also use the then method to register callbacks, and these callbacks will receive a single argument – an object representing the response. See the API signature and type info below for more details.

Shortcut methods

Shortcut methods are also available. All shortcut methods require passing in the URL, and request data must be passed in for POST/PUT requests.

  $sailsSocket.get('/someUrl').success(successCallback);
  $sailsSocket.post('/someUrl', data).success(successCallback);

Complete list of shortcut methods:

  • $sailsSocket.get
  • $sailsSocket.head
  • $sailsSocket.post
  • $sailsSocket.put
  • $sailsSocket.delete
  • $sailsSocket.subscribe

Setting Headers

The $sailsSocket service will automatically add certain headers to all requests. These defaults can be fully configured by accessing the $sailsSocketProvider.defaults.headers configuration object, which currently contains this default configuration:

  • $sailsSocketProvider.defaults.headers.common (headers that are common for all requests):
    • Accept: application/json, text/plain, * / *
  • $sailsSocketProvider.defaults.headers.post: (header defaults for POST requests)
    • Content-Type: application/json
  • $sailsSocketProvider.defaults.headers.put (header defaults for PUT requests)
    • Content-Type: application/json

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. `$sailsSocketProvider.defaults.headers.get = { 'My-Header' : 'value' }.

The defaults can also be set at runtime via the $sailsSocket.defaults object in the same fashion. For example:

module.run(function($sailsSocket) {
  $sailsSocket.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
});

In addition, you can supply a headers property in the config object passed when calling $sailsSocket(config), which overrides the defaults without changing them globally.

Transforming Requests and Responses

Both requests and responses can be transformed using transform functions. By default, Angular applies these transformations:

Request transformations:

  • If the data property of the request configuration object contains an object, serialize it into JSON format.

Response transformations:

  • If XSRF prefix is detected, strip it (see Security Considerations section below).
  • If JSON response is detected, deserialize it using a JSON parser.

To globally augment or override the default transforms, modify the $sailsSocketProvider.defaults.transformRequest and $sailsSocketProvider.defaults.transformResponse properties. These properties are by default an array of transform functions, which allows you to push or unshift a new transformation function into the transformation chain. You can also decide to completely override any default transformations by assigning your transformation functions to these properties directly without the array wrapper. These defaults are again available on the $sailsSocket factory at run-time, which may be useful if you have run-time services you wish to be involved in your transformations.

Similarly, to locally override the request/response transforms, augment the transformRequest and/or transformResponse properties of the configuration object passed into $sailsSocket.

Interceptors

Before you start creating interceptors, be sure to understand the $q and deferred/promise APIs.

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests. The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

The interceptors are service factories that are registered with the $sailsSocketProvider by adding them to the $sailsSocketProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

There are two kinds of interceptors (and two kinds of rejection interceptors):

  • request: interceptors get called with http config object. The function is free to modify the config or create a new one. The function needs to return the config directly or as a promise.
  • requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
  • response: interceptors get called with http response object. The function is free to modify the response or create a new one. The function needs to return the response directly or as a promise.
  • responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

```js // register the interceptor as a service $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { return { // optional method 'request': function(config) { // do something on success return config || $q.when(config); },

  // optional method
 'requestError': function(rejection) {
    // do something on error
    if (canRecover(rejection)) {
      return responseOrNewPromise
    }
    return $q.reject(rejection);
  },



  // optional method
  'response': function(response) {
    // do something on success
    return response || $q.when(response);
  },

  // optional method
 'responseError': function(rejection) {
    // do something on error
    if (canRecover(rejection)) {
      return responseOrNewPromise
    }
    return $q.reject(rejection);
  }
};

});

$sailsSocketProvider.interceptors.push('mySocketInterceptor');

// alternatively, register the interceptor via an anonymous factory $sailsSocketProvider.interceptors.push(function($q, dependency1, dependency2) { return { 'request': function(config) { // same as above },

  'response': function(response) {
     // same as above
  }
};

});

Dependencies

Usage

$sailsSocket(config);

Parameters

ParamTypeDetails
configobject

Object describing the request to be made and how it should be processed. The object has following properties:

  • method{string} – HTTP method (e.g. 'GET', 'POST', etc)
  • url{string} – Absolute or relative URL of the resource that is being requested.
  • params{Object.<string|Object>} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
  • data{string|Object} – Data to be sent as the request message data.
  • headers{Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent.
  • xsrfHeaderName{string} – Name of HTTP header to populate with the XSRF token.
  • xsrfCookieName{string} – Name of cookie containing the XSRF token.
  • transformRequest{function(data, headersGetter)|Array.<function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.
  • transformResponse{function(data, headersGetter)|Array.<function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version.
  • cache{boolean|Cache} – If true, a default $sailsSocket cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
  • timeout{number|Promise} – timeout in milliseconds, or a promise that should abort the request when resolved.
  • withCredentials - {boolean} - whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information.
  • responseType - {string} - see requestType.

Returns

Promise

Returns a promise object with the standard then method and two http specific methods: success and error. The then method takes two arguments a success and an error callback which will be called with a response object. The success and error methods take a single argument - a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are destructured representation of the response object passed into the then method. The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions.
  • status{number} – HTTP status code of the response.
  • headers{function([headerName])} – Header getter function.
  • config{Object} – The configuration object that was used to generate the request.
  • statusText{string} – HTTP status text of the response.

Methods

Properties