• Stars
    star
    313
  • Rank 133,714 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated almost 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A lightweight data model library for Ember.js

Ember RESTless Build Status

RESTless is a lightweight data model library for Ember.js.

Out of the box, you can quickly and easily map data between a JSON REST API and your Ember.js application. It's goal is to create a simple API to perform CRUD operations without having to write ajax requests or handle model serialization & deserialization. RESTless is not a client-side data store.

See the full API documentation.

See the change log for the latest features and API changes.

Guide

Getting started

Install:

npm install --save-dev ember-restless

Module usage:

import RL from 'ember-restless'; // imports entire library
import { Model, attr } from 'ember-restless'; // or import individual modules

Initializer:
Create an initializer in your ember-cli app: app/initializers/restless.js:

import Ember from 'ember';
import { Client } from 'ember-restless';

export function initialize() {
  var application = arguments[1] || arguments[0];
  application.set('Client', Client.create());
}

export default {
  initialize,
  name: 'restless',
  before: 'RESTless.Client'
};

Defining a RESTAdapter

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

import { RESTAdapter } from 'ember-restless';

var adapter = RESTAdapter.create({
  host: 'http://api.example.com',
  namespace: 'v1'
});

You should then set your custom adapter as a property of the Client, created above.

application.set('Client', Client.create({
  adapter: adapter
}));

Models

Each model you create should extend Model:

import { Model, attr } from 'ember-restless';

var Post = Model.extend({
  title:       attr('string'),
  isPublished: attr('boolean'),
  readCount:   attr('number'),
  createdAt:   attr('date')
});

Post.reopenClass({
  resourceName: 'post'
});

export default Post;

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.

Relationships

For one-to-one relationships use the belongsTo attribute helper.

var User = Model.extend({
  name: attr('string'),
  role: attr('number')
});

User.reopenClass({
  resourceName: 'user'
});

var Profile = Model.extend({
  user: belongsTo('user')
});

For one-to-many relationships, use the hasMany helper.
For example, if a Post model contains an array of Tag models:

var Tag = Model.extend({
  name: attr('string'),
  count: attr('number')
});

var Post = Model.extend({
  tags: hasMany('tag')
});

Currently, all relational data should be embedded in the response. Also, see Loading records.

Finding records

Use the find() method to retrieve records.

To find all records of type 'post':

var posts = Post.find();
// => Array of 'post' records

To find a 'post' with an primary key of 1:

var post = Post.find(1);
// => 'post' record instance

To use a query to find records:

var posts = Post.find({ isPublished: true });
// => Array of 'post' records

To return a Promise when finding records, use fetch(). See the promises section.

Creating records

Create records like you would a normal Ember Object:

var post = Post.create({
  title: 'My First Post'
});

Saving records

Simply call: saveRecord()
The Adapter will automatically POST to save a new record, or PUT to update an existing record.

var post = Post.create({ title: 'My First Post' });
post.saveRecord();

Updating:

post.set('title', 'My Very First Post');
post.saveRecord();

Deleting records

The Adapter will delete the record from the data store, then destroy the object when complete:

post.deleteRecord();

Reloading records

To refresh an existing record from the data store: reloadRecord()

var post = Post.find(1);
// ...
post.reloadRecord();

Loading records

You can manually populate records using raw data.
Use the load and loadMany convenience methods:

var post = Post.create();

// The following could have been retrieved from a separate ajax request
var commentData = { comment: { id: 101, message: 'This is awesome!' } };
var comment = Comment.load(commentData);
post.set('comment', comment);

var postTagData = [
  { id: 1, name: 'technology', count: 50 },
  { id: 2, name: 'entertainment', count: 11 }
];
var tags = Tag.loadMany(postTagData);
post.set('tags', tags);

Model lifecycle and state

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 = 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 = Post.find();

allPosts.on('didLoad', function() {
  console.log('posts retrieved!');
});
allPosts.on('becameError', function(error) {
  console.log('error getting posts!');
});

Promises

CRUD actions return promises (saveRecord(), deleteRecord(), reloadRecord()), allowing you to do the following:

var post = 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 = Post.fetch().then(function(records) {
  // Success!
}, function(error) {
  // Error!
});

Using the router:

export default Ember.Route.extend({
  model: function() {
    Post.fetch();
  }
});

Advanced

Changing resource endpoints

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

var CurrentUser = Model.extend();
CurrentUser.reopenClass({
  resourceName: 'user'
});

Custom plurals configuration

You can use a custom adapter to set irregular plural resource names

adapter.configure('plurals', {
  person: 'people'
});

Changing the the primary key for a model

The primary key for all models defaults to 'id'. You can customize it per model class to match your API:

adapter.map('post', {
  primaryKey: 'slug'
});

Mapping different property keys

For example, if your JSON has a key lastNameOfPerson and the desired attribute name is lastName:

var Person = Model.extend({
  lastName: attr('string')
});
apdater.map('person', {
  lastName: { key: 'lastNameOfPerson' }
});

Sending headers and/or data with every request (e.g. api keys)

To add a header to every ajax request:

var adapter = RESTAdapter.create({
  headers: { 'X-API-KEY' : 'abc1234' }
});

To add data to every request url:

var adapter = RESTAdapter.create({
  defaultData: { api_key: 'abc1234' }
});

Results in e.g. User.find() => http://api.example.com/users?api_key=abc1234

Forcing content type extensions

If you want the RESTAdapter to add extensions to requests: For example /users.json and /user/1.json

var adapter = RESTAdapter.create({
  useContentTypeExtension: true
});

Default attribute values

You can define default values to assign to newly created instances of a model:

var User = Model.extend({
  name: attr('string'),
  role: attr('number', { defaultValue: 3 })
});

Read-only attributes

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:

var Person = Model.extend({
  firstName: attr('string'),
  lastName: attr('string'),
  createdAt: attr('date', { readOnly: true })
});

Read-only models

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'.

import { ReadOnlyModel } from 'ember-restless';
var Post = ReadOnlyModel.extend({
...
});

Custom transforms

You can add custom transforms to modify data coming from and being sent to the persistence layer.

import { Transform } from 'ember-restless';
adapter.registerTransform('timeAgo', Transform.create({
  deserialize: function(serialized) {
    // return a custom date string, such as: '5 minutes ago'
  }
}));
var Comment = Model.extend({
  createdAt: attr('timeAgo')
});

Building

npm run build

Testing

Install test dependencies: bower install

npm test

or open tests/index.html in a browser

More Repositories

1

mobiledoc-kit

A toolkit for building WYSIWYG editors with Mobiledoc
JavaScript
1,549
star
2

shep

A framework for building JavaScript Applications with AWS API Gateway and Lambda
JavaScript
377
star
3

ts-eager

Fast TypeScript runner using esbuild for eager compilation
JavaScript
216
star
4

bluestream

A collection of streams that work well with promises (through, map, reduce). Think Through2 with promises
TypeScript
103
star
5

ember-mobiledoc-editor

JavaScript
86
star
6

streaming-iterables

A Swiss army knife for async iterables. Designed to replace your streams.
TypeScript
43
star
7

ember-cli-amp

render valid Google's Accelerated Mobile Pages project (AMP) pages with your ember app and Fastboot
JavaScript
32
star
8

mobiledoc-dom-renderer

JavaScript
25
star
9

graphql-helper

A simple helper library for constructing GraphQL queries.
JavaScript
24
star
10

ember-cli-deploy-fastboot-lambda

JavaScript
23
star
11

nemesis-db

An Open Source Port of the Gradius API Storage Engine
TypeScript
22
star
12

sammie

Serverless Application Model Made Infinitely Easier
JavaScript
21
star
13

coloring-palette

🎨 🖌 A library to generate color palettes based on Material UI's approach to colors
TypeScript
20
star
14

radredis

Basic redis backed object modeling for Node.
JavaScript
19
star
15

dynamo-graph

Low-level graph operations implemented on DynamoDB
JavaScript
18
star
16

ember-mobiledoc-dom-renderer

Render mobiledoc documents in an ember app
JavaScript
15
star
17

ember-cli-image

Stateful image components for Ember.js
JavaScript
14
star
18

statsd-lambda

A simple UDP based statsd client designed for functions as a service
TypeScript
12
star
19

aws-sudo

JavaScript
10
star
20

radql

Opinionated, service-oriented, GraphQL architecture
JavaScript
9
star
21

yajsondiff

Yet another JSON diff utility, for generating and applying patches
JavaScript
8
star
22

mobiledoc-text-renderer

A text renderer for Mobiledoc
JavaScript
7
star
23

redis_assist

Redis Assist - Easy Redis Backed Object Modeling
Ruby
7
star
24

redis-loader

A Redis command batcher
TypeScript
6
star
25

chai-graphql

GraphQL response matcher for Chai assertion library
JavaScript
6
star
26

mobiledoc-vdom-renderer

🔮 Render Mobiledoc as VDOM by passing your React or React-like `createElement` function
TypeScript
6
star
27

wordpress-exporter

WordPress model exporter for Bustle
PHP
5
star
28

broccoli-test-builder

JavaScript
4
star
29

gziptest

JavaScript
4
star
30

broccoli-multi-builder

JavaScript
4
star
31

ember-cli-image-imgix

An addon that builds on top of ember-cli-image to add imgix.com support
JavaScript
3
star
32

wool

Lambda Wrapper
JavaScript
3
star
33

mobiledoc-html-renderer

Deprecated. See https://github.com/bustlelabs/mobiledoc-dom-renderer#rendering-html
JavaScript
3
star
34

ember-mobiledoc-text-renderer

JavaScript
3
star
35

fastText-layer

fastText for AWS Lambda
Shell
3
star
36

ember-cli-image-lazy

An addon that builds on top of ember-cli-image to add lazy-loaded image support.
JavaScript
2
star
37

slugify

JavaScript
2
star
38

broccoli-amd-loader

JavaScript
2
star
39

max-socket

Prototype socket server for our internal CMS. Used for talk at Ember NYC.
JavaScript
2
star
40

apple-news-cli

A node CLI tool for publishing to Apple News
JavaScript
1
star
41

mobiledoc-jsx-renderer

TypeScript
1
star
42

s3_master

Manage S3 bucket policies without cloudformation
Ruby
1
star
43

graphql-loader

GraphQL Loader for Webpack
TypeScript
1
star
44

statsd-docker

Statsd dockerized service using elasticsearch-statsd-backend
Dockerfile
1
star
45

mobiledoc-apple-news-renderer

JavaScript
1
star