ember-api-actions0.2.8 • Public • Published
Trigger "remote" actions on ember-data resources that don't fit into typical CRUD RESTful API design.
For example, if you have restful API endpoints like
GET /fruits POST /fruits GET /fruits/123 PUT /fruits/123 DELETE /fruits/123
What happens if you want to consume API endpoints like these:
PUT /fruits/123/ripen GET /fruits/citrus
Example Rails API routes:
Rails.application.routes.draw doresources :fruits domember doput 'ripen' to: 'fruits#ripen'endcollection doget 'citrus' to: 'fruits#citrus_index'endendend
This is not immediately intuitive with ember-data, and these kinds of API endpoints can be found in widely-used RESTful APIs. This library aims to make it easy.
# ember-cli >= 0.2.3ember install ember-api-actions# ember-cli < 0.2.3ember install:addon ember-api-actions
You can then add these "actions" (not to be confused with client-side ember.js actions) to your ember-data model
;;const attr = DS;Model;
you can then call these functions, and they will initiate API requests and return you the promise
// Pass data in, it will be sent in the POST or PUT request payloadmyRecord;
Before and After Hooks
after hooks to customize the request and response. The hooks are available for both member actions and collection actions.
Say you'd like to use ember-data to serialize your model, passing in only some, additional specific changes. You can do that like so:
eat:// Call it like this:model;// JSON API request payload would look something like:data: id: '1' type: 'fruit' attributes: name: 'apple' is_eaten: true
The after hook receives the response payload as an argument.
You can use the
after hook to push into the store. We've included a helper called
serializeAndPush to do this.
Warning this implemention only works for JSON API, but it should be easy to write your own
after hook to handle your use case. Have a look at the implementation of
serializeAndPush for an example.
ember-api-actions generates URLs and ajax configuration via ember-data adapters. It will identify the appropriate adapter, and call the
ajaxOptions methods to send a JSON request similar to way conventional ember-data usage works.
Customizing your adapter should customize requests sent out via this library, along with any other ember-data requests.
ember-api-actions uses the following methods on DS.Adapter
- buildURL - for generating an action's URL
- ajax (private) - to actually make the API request and return a promise
This addon is known to work with certain combinations of ember.js and ember-data
git clonethis repository
- Visit your app at http://localhost:4200.
ember try:testallto test your addon against multiple Ember versions)
ember test --server
Make sure to set
ALLOW_DEPRECATIONS=true or the tests will raise
errors on deprecation
For more information on using ember-cli, visit http://ember-cli.com/.