AngularJs Resources Improved

Simple as hell

Simplest possible resource is created like this.

restFactory("Person");

This provides default set of methods for ajax calls.

Invocation examples

Invocation Method Url Request Body
Person.get({ idPerson: 1}, [successFn], [errorFn]) GET /api/persons/1
Person.query({ sex: 'male'}, [successFn], [errorFn]) GET /api/persons { sex: 'male'}
Person.listByIds({ ids: [1,2,3,4,5]}, [successFn], [errorFn]) GET /api/persons/listByIds ?ids=1&ids=2&ids=3&ids=4&ids=5
person.$save([successFn], [errorFn]) POST /api/persons { id: 1, firstName: 'John', lastName: 'Doe' }
person.$update([successFn], [errorFn]) PUT /api/persons { id: 1, firstName: 'John', lastName: 'Doe' }

Methods

Invocation Result
Resource.get([parameters], [success], [error]) Returns single object of type that match parameters.
Resource.query(([parameters], [success], [error])) Returns array of objects that match parameters.
instance.$save([parameters], postData, [success], [error]) Saves object, sending it's data by POST request.
instance.$update([parameters], postData, [success], [error]) Updates object by sending it's data by PUT request.

More complicated example changes default entityName (root of all urls for this resource), and adds new functions.

restFactory('Login', {
        urlEntityName: 'login',
        additionalFunctions: {
          getUser: { url: "/user" },
          logoff: { url: "/logoff", method: 'POST' },
          login: {
            method: 'POST'
          }
        }
      });

Invocation examples

Invocation Method Url Request Body
Login.getUser([successFn], [errorFn]) GET /api/login/user
Login.logoff([successFn], [errorFn]) POST /api/login/logoff
Login.login({ username: 'doe', password: 'pass' }, [successFn], [errorFn]) GET /api/login/user { username: 'doe', password: 'pass' }

Configuration parameters

Parameter Description
parentName If present, this entity represents other's entity child. So urls will not be like /api/urlEntityName/, but /api/parentName//urlEntityName/.
urlEntityName Normally urlEntityName is automatically builded by concatenating passed module name and 's'. But sometimes you don't want this convention. Then by setting urlEntityName you may change default behaviour.
additionalFunctions Parameter containing additional functions for resource construction.

How resources work

This simple module implements a couple of conventions for resource processing.

  • All methods have id[name] parameter. So when building factory by restFactory("Person");, get method has idPerson parameter for setting id.
  • Processes first level and child level entities. It is not possible to process child's child.
  • Adds update() method that is not present in AngularJs.
  • Adds isNew() method, that returns true if entity has id. That is a marker of db state.

License

This project is licensed under terms of Apache 2.0 License