ResourceFactoryService

ResourceFactoryService

new ResourceFactoryService(name, url, options)

Factory that gives a constructor function for creating a resource service. The resource service is used to make
calls to the REST-API via the "method" functions. These are the default method functions:

{
    // Undo all changes on the instance using the cache or by reloading the data from the server
    'restore': {method:'GET', isArray:false},
    // Get a single instance from the API
    'get': {method:'GET', isArray:false},
    // Get a single instance from the API bypassing the cache
    'getNoCache': {method:'GET', isArray:false},
    // Get a list of instances from the API
    'query': {method:'GET', isArray:true},
    // Get a list of instances from the API bypassing the cache
    'queryNoCache': {method:'GET', isArray:true},
    // Save a new instance
    'save': {method:'POST', isArray:false},
    // Update an existing instance
    'update': {method:'PATCH', isArray:false},
    // Delete an instance
    'remove': {method:'DELETE', isArray:false},
}

You can extend or override these methods by using the options.extraMethods option.

Each of these methods is available as "static" version on the returned resource class, or as instance
method on a resource instance. The instance methods have a "$" prefix. Each of these methods,
static and instance versions, exists with a "Bg" postfix to make the call in the "background". This
means you do not see a loading bar if you are using angular-loading-bar (http://chieffancypants.github.io/angular-loading-bar/).

Parameters:
Name Type Description
name String

Name of the resource service

url String

URL to the resource

options Object

Options for the resource

Properties
Name Type Description
stripTrailingSlashes Boolean

Strip trailing slashes from request URLs. Defaults to false.

withCredentials Boolean

Include credentials in CORS calls. Defaults to true.

ignoreLoadingBar Boolean

Ignore the resource for automatic loading bars. Defaults to false.

generatePhantomIds Boolean

Generate IDs for phantom records created via the new method. Defaults to true.

phantomIdGenerator ResourcePhantomIdFactoryService

Phantom ID generator instance used for generating phantom IDs. Defaults to ResourcePhantomIdNegativeInt.

dependent Array.<String>

List of resource services to clean the cache for on modifying requests.

extraMethods Object

Extra request methods to put on the resource service. Works the same way as actions known from ng-resource. Defaults to {}.

extraFunctions Object

Extra functions to put on the resource service instance.

extraParamDefaults Object

Extra default values for url parameters. Works the same way as defaultParams known from ng-resource. Defaults to {}.

pkAttr String

Attribute name where to find the ID of objects. Defaults to "pk".

urlAttr String

Attribute name where to find the URL of objects. Defaults to "url".

dataAttr String

Attribute name where to find the data on call results. Defaults to null.

useDataAttrForList String

Use the dataAttr for list calls (e.g. query). Defaults to true.

useDataAttrForDetail String

Use the dataAttr for detail calls (e.g. get). Defaults to false.

queryDataAttr String

Deprecated: Attribute name where to find the data on call results. Note that this option does the same as setting dataAttr. Defaults to null.

queryTotalAttr String

Attribute name where to find the total amount of data on the query call (resource list calls). Defaults to null.

cacheClass String

Resource cache class constructor function to use (see ResourceCacheService). Defaults to ResourceCacheService.

toInternal function

Function to post-process data coming from response. Gets obj, headersGetter and status and should return the processed obj.

fromInternal function

Function to post-process data that is going to be sent. Gets obj and headersGetter and should return the processed obj.

Source:
Examples
// Basic GET calls
inject(function (ResourceFactoryService, $q) {
    var
        service = ResourceFactoryService('Test1ResourceService', 'http://test/:pk/');

    $httpBackend.expect('GET', 'http://test/').respond(200, [{pk: 1}, {pk: 2}]);
    $httpBackend.expect('GET', 'http://test/1/').respond(200, {pk: 1});
    $httpBackend.expect('GET', 'http://test/2/').respond(200, {pk: 2});

    $q.when()
        .then(function () {
            return service.query().$promise;
        })
        .then(function () {
            return service.get({pk: 1}).$promise;
        })
        .then(function () {
            return service.get({pk: 2}).$promise;
        })
        .then(done);

    $httpBackend.flush();
    $httpBackend.verifyNoOutstandingRequest();
});
// GET calls with query parameters
inject(function (ResourceFactoryService, $q) {
    var
        service = ResourceFactoryService('Test2ResourceService', 'http://test/:pk/');

    $httpBackend.expect('GET', 'http://test/?filter=1').respond(200, [{pk: 1}, {pk: 2}]);

    $q.when()
        .then(function () {
            return service.query({filter: 1}).$promise;
        })
       .then(done);

    $httpBackend.flush();
    $httpBackend.verifyNoOutstandingRequest();
});
// Process list GET calls with data attribute
inject(function (ResourceFactoryService, $q) {
    var
        service = ResourceFactoryService('TestResourceService', 'http://test/:pk/', {
            dataAttr: 'data'
        });

    expect(service.getDataAttr()).toBe('data');

    $httpBackend.expect('GET', 'http://test/').respond(200, {data: [{pk: 1}, {pk: 2}]});
    $httpBackend.expect('GET', 'http://test/1/').respond(200, {pk: 1});

    $q.when()
        .then(function () {
            return service.query().$promise;
        })
        .then(function (result) {
            expect(result.length).toBe(2);
        })
        .then(function () {
            return service.get({pk: 1}).$promise;
        })
        .then(function (result) {
            expect(result.pk).toBe(1);
        })
        .then(done);

    $httpBackend.flush();
    $httpBackend.verifyNoOutstandingRequest();
});
// Access attributes outside the data attribute
inject(function (ResourceFactoryService, $q) {
    var
        service = ResourceFactoryService('TestResourceService', 'http://test/:pk/', {
            dataAttr: 'data'
        });

    $httpBackend.expect('GET', 'http://test/').respond(200, {prop1: 123, data: [{pk: 1}, {pk: 2}]});

    $q.when()
        .then(function () {
            return service.query().$promise;
        })
        .then(function (result) {
            expect(result.$meta.prop1).toBe(123);
        })
        .then(done);

    $httpBackend.flush();
    $httpBackend.verifyNoOutstandingRequest();
});
// Resource and instance level methods
inject(function (ResourceFactoryService) {
    var
        service = ResourceFactoryService('TestResourceService', 'http://test/:pk/'),
        instance = service.new();

    expect(service.restore).toBeDefined();
    expect(service.get).toBeDefined();
    expect(service.getNoCache).toBeDefined();
    expect(service.query).toBeDefined();
    expect(service.queryNoCache).toBeDefined();
    expect(service.save).toBeDefined();
    expect(service.update).toBeDefined();
    expect(service.patch).toBeDefined();
    expect(service.remove).toBeDefined();

    expect(instance.$restore).toBeDefined();
    expect(instance.$get).toBeDefined();
    expect(instance.$getNoCache).toBeDefined();
    expect(instance.$query).toBeDefined();
    expect(instance.$queryNoCache).toBeDefined();
    expect(instance.$save).toBeDefined();
    expect(instance.$update).toBeDefined();
    expect(instance.$patch).toBeDefined();
    expect(instance.$remove).toBeDefined();
});

Methods

createStore(instancesopt) → {ResourceStore}

Creates a new store for the resource

Parameters:
Name Type Attributes Description
instances <optional>

List of instances that should be managed by the new store

Source:
Returns:

New store instance

Type
ResourceStore

filter(filtersopt) → {Object}

Queries the resource with the configured filters.

Parameters:
Name Type Attributes Description
filters Object <optional>

Object holding filter attributes

Source:
Returns:

Query result object

Type
Object

filterInstancesByAttr(instances, attrName, attrValue) → {Array.<ResourceInstance>}

Gets a list of instances from the given instances where the given attribute name matches
the given attribute value.

Parameters:
Name Type Description
instances Array.<ResourceInstance>

List of instances to filter

attrName String

Attribute name to filter on

attrValue *

Value to filter for

Source:
Returns:

Filtered list of instances

Type
Array.<ResourceInstance>

filterNoCache(filtersopt) → {Object}

Queries the resource with the configured filters without using the cache.

Parameters:
Name Type Attributes Description
filters Object <optional>

Object holding filter attributes

Source:
Returns:

Query result object

Type
Object

findFromCacheByPk(pkValue) → {Array.<ResourceInstance>}

Gets all items from cache that match the given PK value. If there is no item on the
cache that matches, this method returns an empty array. Note that the cache TTL is ignored.

Parameters:
Name Type Description
pkValue String | int

PK value to search for

Source:
Returns:

Search results data

Type
Array.<ResourceInstance>

firstFromCacheByPk(pkValue) → {ResourceInstance|undefined}

Gets the first item from cache that matches the given PK value. If there is no item on the
cache that matches, this method returns undefined. Note that the cache TTL is ignored.

Parameters:
Name Type Description
pkValue String | int

PK value to search for

Source:
Returns:

Search result data

Type
ResourceInstance | undefined

getCache() → {ResourceCacheService}

Gets the cache instance.

Source:
Returns:

Cache class instance

Type
ResourceCacheService

getCacheClass() → {function}

Gets the cache class

Source:
Returns:

Cache class

Type
function

getDataAttr() → {String|null}

Gets the data attribute name

Source:
Returns:

Data attribute name

Type
String | null

getInstanceByAttr(instances, attrName, attrValue) → {ResourceInstance|null}

Gets the first instance from the given instances where the given attribute name matches
the given attribute value.

Parameters:
Name Type Description
instances Array.<ResourceInstance>

List of instances to filter

attrName String

Attribute name to filter on

attrValue *

Value to filter for

Source:
Returns:

First instances matching the filter

Type
ResourceInstance | null

getInstanceByPk(instances, pkValue) → {ResourceInstance|null}

Gets the first instance from the given instances where the PK attribute has the given value.

Parameters:
Name Type Description
instances Array.<ResourceInstance>

List of instances to filter

pkValue String | int

PK value to filter for

Source:
Returns:

Instance with the given PK

Type
ResourceInstance | null

getPkAttr() → {String|null}

Gets the PK attribute name

Source:
Returns:

PK attribute name

Type
String | null

getQueryDataAttr() → {String|null}

Gets the query data attribute name

Deprecated:
  • Yes
Source:
Returns:

Data attribute name

Type
String | null

getQueryFilters() → {Object}

Returns an object holding the filter data for query request

Source:
Returns:

Filter object

Type
Object

getQueryTotalAttr() → {String|null}

Gets the total attribute name

Source:
Returns:

Total attribute name

Type
String | null

getResourceName() → {String}

Gets the name of the resource.

Source:
Returns:

Resource name

Type
String

isPhantom(instance) → {Boolean|undefined}

Checks if the given instance is a phantom instance (instance not persisted to the REST API yet)

Parameters:
Name Type Description
instance ResourceInstance

Instance to check

Source:
Returns:

If is phantom or not

Type
Boolean | undefined

new(paramsopt) → {ResourceInstance}

Creates a new instance for the resource

Parameters:
Name Type Attributes Description
params Object <optional>

Object holding attributes to set on the resource instance

Source:
Returns:

Resource instance

Type
ResourceInstance

persist(a1opt, a2opt, a3opt, a4opt) → {ResourceInstance}

Saves the given resource instance to the REST API. Uses the $save method if instance
is phantom, else the $update method.

Parameters:
Name Type Attributes Description
a1 Object <optional>

Query params

a2 ResourceInstance <optional>

Instance

a3 function <optional>

Success callback

a4 function <optional>

Error callback

Source:
Returns:

Resource instance

Type
ResourceInstance

setDefaultQueryFilters(defaultFilters) → {Object}

Sets the given filter options if the aren't already set on the filter object

Parameters:
Name Type Description
defaultFilters Object

Object holding filter attributes

Source:
Returns:

Filter object

Type
Object

setQueryFilters(filters) → {Object}

Sets a clone of the given object as the object holding the filter data for query request

Parameters:
Name Type Description
filters Object

Object holding filter attributes

Source:
Returns:

Filter object

Type
Object