ember-restless is a lightweight data persistence library for Ember.js.
Out of the box, it is used to communicate with a JSON REST API to map data between a server and your Ember.js application. ember-restless can be extended to support various other data persistence layers.
One of its main goals is to reproduce much of the simple, useful features of ember-data, while remaining lightweight and stable.
You should use ember-restless if you want to easily perform CRUD operations on your ember models without having to write any ajax or json serialization / deserialization.
See the full API documentation.
See the change log for the latest features and API changes.
- Getting started
- Defining a RESTAdapter
- Defining a 'Client'
- Models
- Promises
- Advanced
- Building
- Tests
- Add-ons
To use in an ember-cli app, simply:
npm install --save-dev ember-restless
For old-school global apps, include ember-restless.js after ember.js.
Namespace
RESTless can be referenced either with the namespace RESTless or the shorthand RL. Similar to Ember and Em
The REST adapter is responsible for communicating with your backend REST service.
Here, you can optionally set the host, and a namespace.
For example, if your REST API is located at http://api.example.com/v1
App.RESTAdapter = RL.RESTAdapter.create({
host: 'http://api.example.com',
namespace: 'v1'
});
Similar to defining the 'Store' using ember-data, instead define the 'Client' for your application. RESTless will automatically detect the Client on your application namespace and initialize RESTless to work with your app.
App.Client = RL.Client.create({
adapter: App.RESTAdapter
});
Each model you create should extend RL.Model:
App.Post = RL.Model.extend({
title: RL.attr('string'),
isPublished: RL.attr('boolean'),
readCount: RL.attr('number'),
createdAt: RL.attr('date')
});
Supported attribute types are string, number, boolean, and date. Defining a type is optional. You can define custom attribute type transforms in your adapter. See the advanced section below.
Note on ES6 modules
If using ES6 modules/ember-cli, you'll need to explicitly define resourceName
on all of your model classes:
var Post = RL.Model.extend({ ... });
Post.reopenClass({
resourceName: 'post'
});
export default Post;
For one-to-one relationships use the belongsTo attribute helper.
App.User = RL.Model.extend({
name: RL.attr('string'),
role: RL.attr('number')
});
App.Profile = RL.Model.extend({
user: RL.belongsTo('user')
});
For one-to-many relationships, use the hasMany helper.
For example, if a Post
model contains an array of Tag
models:
App.Tag = RL.Model.extend({
name: RL.attr('string'),
count: RL.attr('number')
});
App.Post = RL.Model.extend({
tags: RL.hasMany('tag')
});
Currently, all relational data should be embedded in the response. Also, see Side-loading records.
Use the find()
method to retrieve records.
To find all records of type 'post':
var posts = App.Post.find();
// => Array of 'post' records
To find a 'post' with an primary key of 1
:
var post = App.Post.find(1);
// => 'post' record instance
To use a query to find records:
var posts = App.Post.find({ isPublished: true });
// => Array of 'post' records
To return a Promise when finding records, use fetch()
. See the promises section.
Create records like you would a normal Ember Object:
var post = App.Post.create({
title: 'My First Post'
});
Simply call: saveRecord()
The Adapter will automatically POST to save a new record, or PUT to update an existing record.
var post = App.Post.create({ title: 'My First Post' });
post.saveRecord();
Updating:
post.set('title', 'My Very First Post');
post.saveRecord();
The Adapter will delete the record from the data store, then destroy the object when complete:
post.deleteRecord();
To refresh an existing record from the data store: reloadRecord()
var post = App.Post.find(1);
// ...
post.reloadRecord();
You can manually populate records using raw data (side-loading).
Use the load
and loadMany
convenience methods:
var post = App.Post.create();
// The following could have been retrieved from a separate ajax request
var commentData = { comment: { id: 101, message: 'This is awesome!' } };
var comment = App.Comment.load(commentData);
post.set('comment', comment);
var postTagData = [
{ id: 1, name: 'technology', count: 50 },
{ id: 2, name: 'entertainment', count: 11 }
];
var tags = App.Tag.loadMany(postTagData);
post.set('tags', tags);
All models have the following state properties added:
- isNew: Record has been created but not yet saved
- isLoaded: Record(s) have been retrieved
- isDirty: The record has local changes that have not yet been stored
- isSaving: Record is in the process of saving
- isError: Record has been attempted to be saved, updated, or deleted but returned an error. Error messages are store in the errors property.
You can subscribe to events that are fired during the lifecycle:
- didLoad
- didCreate
- didUpdate
- becameError
Event Examples:
var post = App.Post.create({ title: 'My First Post' });
post.on('didCreate', function() {
console.log('post created!');
});
post.on('becameError', function(error) {
console.log('error saving post!');
});
post.saveRecord();
var allPosts = App.Post.find();
allPosts.on('didLoad', function() {
console.log('posts retrieved!');
});
allPosts.on('becameError', function(error) {
console.log('error getting posts!');
});
CRUD actions return promises (saveRecord()
, deleteRecord()
, reloadRecord()
), allowing you to do the following:
var post = App.Post.create({
title: 'My First Post'
});
post.saveRecord().then(function(record) {
// Success!
}, function(errors) {
// Error!
});
To take advantage of promises when finding records, use fetch()
instead of find()
fetch()
returns a promise, while find()
will return entities that will update when resolved.
var posts = App.Post.fetch().then(function(records) {
// Success!
}, function(error) {
// Error!
});
Using the router:
App.PostIndexRoute = Ember.Route.extend({
model: function() {
App.Post.fetch();
}
});
Sometimes the name of your Ember model is different than the API endpoint.
For example if a CurrentUser
model needs to point to /users
and /user/1
App.CurrentUser = RL.Model.extend();
App.CurrentUser.reopenClass({
resourceName: 'user'
});
You can use a custom adapter to set irregular plural resource names
App.RESTAdapter.configure('plurals', {
person: 'people'
});
The primary key for all models defaults to 'id'. You can customize it per model class to match your API:
App.RESTAdapter.map('post', {
primaryKey: 'slug'
});
For example, if your JSON has a key lastNameOfPerson
and the desired attribute name is lastName
:
App.Person = RL.Model.extend({
lastName: RL.attr('string')
});
App.RESTAdapter.map('person', {
lastName: { key: 'lastNameOfPerson' }
});
To add a header to every ajax request:
App.RESTAdapter = RL.RESTAdapter.create({
headers: { 'X-API-KEY' : 'abc1234' }
});
To add data to every request url:
App.RESTAdapter = RL.RESTAdapter.create({
defaultData: { api_key: 'abc1234' }
});
Results in e.g. App.User.find()
=> http://api.example.com/users?api_key=abc1234
If you want the RESTAdapter to add extensions to requests:
For example /users.json
and /user/1.json
App.RESTAdapter = RL.RESTAdapter.create({
useContentTypeExtension: true
});
You can define default values to assign to newly created instances of a model:
App.User = RL.Model.extend({
name: RL.attr('string'),
role: RL.attr('number', { defaultValue: 3 })
});
You can make attributes 'read-only', which will exclude them from being serialized and transmitted when saving. For example, if you want to let the backend compute the date a record is created:
App.Person = RL.Model.extend({
firstName: RL.attr('string'),
lastName: RL.attr('string'),
createdAt: RL.attr('date', { readOnly: true })
});
You can make an entire model to read-only. This removes all 'write' methods and provides a slight performance increase since each property won't have to be observed for 'isDirty'.
App.Post = RL.ReadOnlyModel.extend({
...
});
You can add custom transforms to modify data coming from and being sent to the persistence layer.
App.RESTAdapter.registerTransform('timeAgo', RL.Transform.create({
deserialize: function(serialized) {
// return a custom date string, such as: '5 minutes ago'
}
}));
App.Comment = RL.Model.extend({
createdAt: RL.attr('timeAgo')
});
RESTless is abstracted so you can write your own Adapters and Serializers.
App.XMLSerializer = RL.Serializer.create({
...
});
App.SOAPAdapter = RL.Adapter.create({
serializer: App.XMLSerializer
...
});
App.Client = RL.Client.create({
adapter: App.SOAPAdapter
});
If you wish to build ember-restless yourself, you will need node.js and Gulp.
- Install node: http://nodejs.org/
- Install dependencies:
npm install
- Build:
gulp build
- Output will be in
dist/
- Install bower:
npm install -g bower
- Install dependencies:
bower install
- Test:
gulp test
or open tests/index.html in a browser
gulp
default task will both build & test.
RESTless also has the following (unbundled) add-ons, which you can include separately or build yourself:
- Fixture Adapter
- LocalStorage Adapter