ActiveResource.js - Object-relational mapping in Javascript
Welcome to ActiveResource.js, an object relational mapping library for Javascript. ActiveResource.js is designed to make
interacting with resources stored on a RESTful server more straightforward and holistic than simpler solutions like
ngResource
. ActiveResource.js constructs and executes requests and formats responses into
meaningful resource representations on the client side, allowing you to perform CRUD operations, as well
as interact with and modify the various relationships (often known as associations) of resources effortlessly.
ActiveResource.js is inspired heavily by Active Record, the well known ORM for Ruby on Rails. In the same way that Active Record makes interacting with relational databases trivial in most of the use cases that might be required of a server side application, ActiveResource.js hopes to make interacting with RESTful servers trivial in most of the use cases that might be required of a client side application.
The library provides a base class that, when subclassed, sets up a mapping between the new class and an existing resource scope on the server. In the context of an application, these classes are commonly referred to as models. Models can also be connected to other models in two ways: through client side interaction (whose behavior is defined by associations), and by making requests to persist the association on the server.
ActiveResource.js relies heavily on naming in that it uses class and association names to establish mappings between respective resource endpoints, subresource endpoints, and foreign key properties. Although these mappings can be defined explicitly, it's recommended to follow naming conventions, especially when getting started with the library.
WARNING: ActiveResource.js currently only works in browsers. A new release will soon allow it to work in Node, plus change some design decisions to use more universal idioms.
New in 2.0: Resource Libraries (Getting Started)
In order to use ActiveResource, you must first create a resource library to hold configuration data for accessing your resources:
# lib/myLibrary.coffee MyLibrary = ActiveResourcecreateResourceLibrary 'https://example.com/api/v1/'# base url for your server headers: Authorization: 'Basic ...'
Then, you create a resource class for each resource in your library:
# lib/myLibrary/product.coffee this.className = 'Product' this.queryName = 'products' # **or** ::Product extends MyLibraryBase this.className = 'Product' this.queryName = 'products'
Both className
and queryName
are required, and you can see what they do in the configuration section of this page.
Some of the major features include:
- Automated mapping between classes and endpoints, attributes and relationships
this.className = 'Product' this.queryName = 'products'
The Product class is automatically mapped to the RESTful endpoints for product resources on the server, which would all have the URL:
http://example.com/api/v1/products/
- HTTP requests constructable through simple to use chained method calls (a
Relation
)
Productwheretitle: 'A product title'includes'orders'ordercreatedAt: 'desc'allProductselect'title'first5Productpage2perPage1all Productlimit2offset2all Productfind1ProductfindBytitle: 'A product title' Producteach ... Productincludes'orders'merchant: 'currency'all
Method calls like all()
will return a promise, and the response in the promise will be an ActiveResource::Collection
(see below). If the response is expected to be a single resource (find
, findBy
, first
) it will just be that resource.
Note: Due to the current design of JSON API, if you use both select
and includes
in the same Relation
chain, you should add any includes
to select
. For example:
Productincludes'merchant'select'title'all
should be:
Productincludes'merchant'select'title''merchant'all
This is because the JSON API spec defines both attributes and relationships as fields
, which is what the select
method constructs. So
if you want to include a relationship and you also plan on select
ing fields, make sure that you specify any includes as a field using
select
. This does not apply if you only want to use includes
without select
.
- Persistence methods that simplify managing of resources
product = Productbuildtitle: 'A product title'productsave -> if productvalid productpersisted # == true else producterrorsempty # == false Productcreate title: 'A product title' if productvalid ... else productnewRecord # == true Productfirstthen productupdate title: 'A new title' Productfirstthen productdestroy Productfirstthen productreload
- Associations between objects defined by simple class methods
@hasMany 'orders' @belongsTo 'product'
This defines a number of methods on each class. For hasMany
:
product = Productbuildproductorders # collection proxy to use for more queries (see below) productorderstoArray # read productordersbuild # local construction productorderscreate # persisted construction productordersassign # persisted assignment productorderspush # persisted concatenation productordersdelete # persisted deletion of association (not the resources themselves) productordersdeleteAllproductordersreloadproductordersempty # NOTE: Only indicates if the collection currently loaded is empty productorderssize # NOTE: Only gives the size of the collection currently loaded
In regards to association collection proxies, you can work off them just like you would any other ActiveResource Relation
class:
productorderswheretitle: 'A product title'select'title'last10then # result will only be orders related to `product` productordersincludes'merchant'create title: 'A product title' if ordervalid ordermerchant # != null, was included in response else ordererrors
It is important to note that none of the hasMany
methods above will assign the actual target of the association to their result,
nor will the association be considered "loaded." For example:
productorderswheretitle: 'A product title'select'title'last10then orders # != [] productorderstoArray # == [] productassociation'orders'loaded # == false
To accomplish this, one must load the association either in the initial query, or at some later point in time:
Productincludes'orders'firstthen productorderstoArray # != [] productassociation'orders'loaded # == true Productfirstthen productassociation'orders'loaded # == false productloadOrders then -> productassociation'orders'loaded # == true productordersloadTarget then -> productassociation'orders'loaded # == true productordersreload then -> productassociation'orders'loaded # == true
In general, it is best to include every association you'll need to do your business in the very first query.
It is also worth noting that most Relation
methods (and association Relation
methods here) will return promises, and do not
hit any sort of cache. If you want to make a synchronous method call that gives you the current target of the association (loaded or not), you have a few options:
Productincludes'orders'firstthen productordersallcached: true productorderstoArray
There are a number of methods defined for singular associations (hasOne
, belongsTo
) as well:
order = Orderbuildorderproduct # read locally orderloadProduct # read persisted orderassignProduct # assign locally orderupdateProduct # persist assignment orderbuildProduct # local construction ordercreateProduct # persist construction
You should never make a direct assignment like product=
, because ActiveResource is not aware when this happens and it may cause unexpected results.
- Reflections on associations
OrderreflectOnAllAssociationseach reflectionname # == 'product' reflectionmacro # == 'belongsTo' reflectionklass # == Product OrderreflectOnAssociation'product'
- Attribute management
order = Orderbuild orderassignAttributesprice: 5.0orderattributes # == { price: 5.0 }
- Better typing, constantizing, module mixins than Javascript alone
OrderbuildisAOrder # == true OrderbuildisAProduct # == false Orderbuildklass # == Order
this.className = 'Order' MyLibraryconstantize'Order' # == MyLibrary.Order
: -> ActiveResourceextendthisMyModule Ordermethod1 # defined ActiveResourceincludethisMyModule Orderbuildmethod1 # defined
- A wrapper class for Array that is similar to Ruby Array functionality
c = ActiveResource::Collectionbuildproduct1product2 callctoArraycsizecemptycincludeitemcfirstnclastnceach ...cinject ...cmap ...ccompactcflattencjoincpushitemscdeleteitemscclearcselect ...cdetect ...
These make use of Underscore.js. Learn more
This is the class that will be returned from Relation#all()
, etc.
- Customization through properties/options on the library itself, as well as base classes and associations:
ResourceLibrary.baseUrl
ActiveResourcecreateResourceLibrary 'http://example.com/api/v1'
This property is required. It specifies the root URL to the resource server, and all requests for resources in the library will be made relative to this URL.
ResourceLibrary.headers
ActiveResourcecreateResourceLibrary headers: 'Authorization': 'Basic xxx'
This property is optional. It specifies any headers that should be added to every request for resources in the library. The most obvious use case is providing an
Authorization
header if your resource server requires authentication.
ResourceLibrary.constantizeScope
MyLibrary = ActiveResourcecreateResourceLibrary constantizeScope: window this.className = 'Product' MyLibraryconstantize'Product' # == window.Product
This property is optional, and defaults to null. It specifies the object to search properties of when looking up a class name to find a class constant. If null, ActiveResource will search both MyLibrary
and MyLibrary::
, if your resource library variable were named MyLibrary
.
ResourceLibrary.interface
ActiveResourcecreateResourceLibrary interface: MyCustomInterface
This property is optional and defaults to ActiveResource.Interfaces.JsonApi
. Interface
s allow you to define the interface between
a server and ActiveResource, constructing requests from input data, and constructing objects from response data. Right now, the only
interface that is supported is JsonApi
, which is in accordance with the JSON API specification.
Base.className
this.className = 'Product'
This property is required. It is so the library will continue to work in minified environments, where a call to constructor.name
might yield a random result instead of the intended class name.
Base.queryName
this.queryName = 'products'
This property is required. This is the name that will be used in URLs, so a call like Product.all()
will result in an HTTP request GET /api/v1/products
Base.primaryKey
this.primaryKey = 'token'
This property is optional. It tells ActiveResource which property in a response object is the primaryKey of the resource being returned, as well as telling ActiveResource which key to use when making foreign key assignments
Association.className
@hasMany 'specialOrders'className: 'Order' @belongsTo 'product'
This option allows you to name an association by one name, but have that association refer to an existing class of a different name
Association.as
&& Association.polymorphic
@hasMany 'orders'as: 'resource' @hasMany 'orders'as: 'resource' @belongsTo 'resource'polymorphic: true
These options work together to allow for polymorphic associations between models.
Association.inverseOf
@hasMany 'orders'inverseOf: 'product' @belongsTo 'product'inverseOf: 'orders'
This option allows you to define the inverse of an association on a class. Typically, this is done automatically, but there are cases,
like polymorphic relationships, where this cannot be done automatically, and it is extremely useful and highly recommended to provide inverseOf
in those instances.
Association.foreignKey
@hasMany 'orders'foreignKey: 'ownerProductId' @belongsTo 'ownerProduct'className: 'Product' Productfirstthen order = productordersbuild # order.ownerProductId == product.id
This option allows you to define the foreign key that is set on a child association (belongsTo
) when assignments/constructions are
made.
Association.primaryKey
@hasMany 'orders'primaryKey: 'token'foreignKey: 'ownerProductId' @belongsTo 'ownerProduct'className: 'Product' Productfirstthen order = productordersbuild # order.ownerProductId == product.token
This option allows you to define the primary key of the parent association that is assigned as the foreign key to the child association when assignments/constructions are made.
Association.autosave
@hasMany 'orderItems'autosave: true @belongsTo 'order' order = OrderbuildorderItems: OrderItembuildamount: 5.0ordersave # sends orderItems attributes to server too
This option allows you to specify that associated object(s) of a resource should be saved when the resource itself is saved.