All Projects → Exelord → ember-custom-actions

Exelord / ember-custom-actions

Licence: MIT license
Custom API actions for Ember applications

Programming Languages

javascript
184084 projects - #8 most used programming language
Handlebars
879 projects
HTML
75241 projects
Sass
350 projects

Projects that are alternatives of or similar to ember-custom-actions

ember-cli-ifa
Ember CLI addon for injecting fingerprinted asset map file into Ember app
Stars: ✭ 54 (-26.03%)
Mutual labels:  ember, ember-addon
ember-cordova
CLI for Ember/Cordova/Crosswalk Applications
Stars: ✭ 16 (-78.08%)
Mutual labels:  ember, ember-addon
ember-best-language
🏳 A FastBoot-enabled addon to detect the best language for your user.
Stars: ✭ 18 (-75.34%)
Mutual labels:  ember, ember-addon
ember-get-config
Get `config/environment` from anywhere, even addons!!!
Stars: ✭ 63 (-13.7%)
Mutual labels:  ember, ember-addon
ember-useragent
An Ember addon for Fastboot-enabled UserAgent parsing via UAParser.js.
Stars: ✭ 34 (-53.42%)
Mutual labels:  ember, ember-addon
ember-autoresize-modifier
Autoresize Element Modifier for Ember.js
Stars: ✭ 15 (-79.45%)
Mutual labels:  ember, ember-addon
ember-link
Link primitive to pass around self-contained route references. It's {{link-to}}, but better!
Stars: ✭ 50 (-31.51%)
Mutual labels:  ember, ember-addon
ember-on-modifier
Implements the `{{on eventName this.someAction}}` element modifier from https://github.com/emberjs/rfcs/blob/master/text/0471-on-modifier.md
Stars: ✭ 37 (-49.32%)
Mutual labels:  ember, ember-addon
ember-query-params
Ember service for your query params
Stars: ✭ 44 (-39.73%)
Mutual labels:  ember, ember-addon
ember-cli-yadda
Write cucumber specs for ember-cli applications
Stars: ✭ 41 (-43.84%)
Mutual labels:  ember, ember-addon
ember-fastboot-app-tests
FastBoot testing support for Ember apps
Stars: ✭ 17 (-76.71%)
Mutual labels:  ember, ember-addon
ember-google-analytics-embed
An Ember Addon for adding analytics visualizations using the Google Analytics Embed API.
Stars: ✭ 26 (-64.38%)
Mutual labels:  ember, ember-addon
ember-cli-g-maps
Deprecated Google Maps Addon
Stars: ✭ 58 (-20.55%)
Mutual labels:  ember, ember-addon
ember-named-yields
Named Yields for Ember Components
Stars: ✭ 17 (-76.71%)
Mutual labels:  ember, ember-addon
ember-content-loader
Easy, customizable content placeholders / skeletons screens
Stars: ✭ 41 (-43.84%)
Mutual labels:  ember, ember-addon
ember-foxy-forms
Ember Addon for Making Foxy Forms
Stars: ✭ 27 (-63.01%)
Mutual labels:  ember, ember-addon
ember-lazy-responsive-image
Generate and render responsive, lazy loaded, LQIP enabled images
Stars: ✭ 14 (-80.82%)
Mutual labels:  ember, ember-addon
ember-responsive-image
Automatically generate resized images at build-time, optimized for the responsive web, and using components to render them easily as <picture> elements.
Stars: ✭ 103 (+41.1%)
Mutual labels:  ember, ember-addon
ember-event-helpers
Complimentary event template helpers to the {{on}} modifier
Stars: ✭ 33 (-54.79%)
Mutual labels:  ember, ember-addon
ember-ref-bucket
This is list of handy ember primitives, created to simplify class-based dom workflow
Stars: ✭ 31 (-57.53%)
Mutual labels:  ember, ember-addon

Ember Custom Actions Logo

Ember Custom Actions is a package for defining custom API actions, dedicated for Ember 2.16 (and higher) applications.

Getting started

Demo

Before you will start with documentation check our demo app: Ember-Custom-Actions Website

Installation

ember install ember-custom-actions

Documentation

Model actions

To define custom action like: posts/1/publish you can use modelAction(path, options) method with arguments:

  • path - url of the action scoped to our api (in our case it's publish)
  • options - optional parameter which will overwrite the configuration options
import Model from 'ember-data/model';
import { modelAction } from 'ember-custom-actions';

export default Model.extend({
  publish: modelAction('publish', { pushToStore: false }),
});

Usage

let user = this.get('currentUser');
let postToPublish = this.get('store').findRecord('post', 1);
let payload = { publisher: user };

postToPublish.publish(payload, /*{ custom options }*/).then((status) => {
  alert(`Post has been: ${status}`)
}).catch((error) => {
  console.log('Here are your serialized model errors', error.serializedErrors);
});

Resource actions

To a define custom action like: posts/favorites you can use resourceAction(actionId/path, options) method with arguments:

  • path - url of the action scoped to our api (in our case it's favorites)
  • options - optional parameter which will overwrite the configuration options
import Model from 'ember-data/model';
import { resourceAction } from 'ember-custom-actions';

export default Model.extend({
  favorites: resourceAction('favorites', { method: 'GET' }),
});

Usage

let user = this.get('currentUser');
let emptyPost = this.get('store').createRecord('post');
let payload = { user };

emptyPost.favorites(payload, /*{ custom options }*/).then((favoritesPosts) => {
  console.log(favoritesPosts);
}).finally(()=>{
  emptyPost.deleteRecord();
});

Custom actions

To define customAction and customize it by using ember-data flow, adapters and serializer you can use customAction(actionId, options) method with arguments:

  • actionId - id of the action which can be handled later on in adpaters and serializers
  • options - optional parameter which will overwrite the configuration options

If you want to customize your request in your adapter please, implement our adapter mixin:

import JSONAPIAdapter from 'ember-data/adapters/json-api';
import { AdapterMixin } from 'ember-custom-actions';

export default JSONAPIAdapter.extend(AdapterMixin);

Now you can customize following methods in the adpater:

urlForCustomAction

You can define your custom path for every customAction by adding a conditional:

export default JSONAPIAdapter.extend(AdapterMixin, {
  urlForCustomAction(modelName, id, snapshot, actionId, queryParams) {
    if (actionId === 'myPublishAction') {
      return 'https://my-custom-api.com/publish'
    }

    return this._super(...arguments);
  }
});

If you would like to build custom modelAction you can do it by:

import { AdapterMixin } from 'ember-custom-actions';

export default JSONAPIAdapter.extend(AdapterMixin, {
  urlForCustomAction(modelName, id, snapshot, actionId, queryParams) {
    if (requestType === 'myPublishAction') {
      return `${this._buildURL(modelName, id)}/publish`;
    }

    return this._super(...arguments);
  }
});

methodForCustomAction

You can define your custom method for every customAction by adding a conditional:

import { AdapterMixin } from 'ember-custom-actions';

export default JSONAPIAdapter.extend(AdapterMixin, {
  methodForCustomAction(params) {
    if (params.actionId === 'myPublishAction') {
      return 'PUT';
    }

    return this._super(...arguments);
  }
});

headersForCustomAction

You can define your custom headers for every customAction by adding a conditional:

import { AdapterMixin } from 'ember-custom-actions';

export default JSONAPIAdapter.extend(AdapterMixin, {
  headersForCustomAction(params) {
    if (params.actionId === 'myPublishAction') {
      return {
        'Authorization-For-Custom-Action': 'mySuperToken123'
      };
    }

    return this._super(...arguments);
  }
});

dataForCustomAction

You can define your custom data for every customAction by adding a conditional:

import { AdapterMixin } from 'ember-custom-actions';

export default JSONAPIAdapter.extend(AdapterMixin, {
  dataForCustomAction(params) {
    if (params.actionId === 'myPublishAction') {
      return {
        myParam: 'send it to the server'
      };
    }

    return this._super(...arguments);
  }
});

params contains following data: data, actionId, modelId, model

Configuration

You can define your custom options in your config/environment.js file

module.exports = function(environment) {
  var ENV = {
    'emberCustomActions': {
      method: 'POST',
      data: {},
      headers: {},
      queryParams: {},
      ajaxOptions: {},
      adapterOptions: {},
      pushToStore: false,
      responseType: null,
      normalizeOperation: ''
    },
  };

  return ENV;
}

method

Default method of the request (GET, PUT, POST, DELETE, etc..)

headers

An object {} of custom headers. Eg:

{
  'my-custom-auth': 'mySuperToken123'
}

ajaxOptions

Your own ajax options. ** USE ONLY IF YOU KNOW WHAT YOU ARE DOING! ** Those properties will be overwritten by ECU.

pushToStore

If you want to push the received data to the store, set this option to true

normalizeOperation

You can define how your outgoing data should be serialized


Exemplary data:
```js
{
  firstParam: 'My Name',
  colors: { rubyRed: 1, blueFish: 3 }
}

After using a dasherize transformer our request data will turn into:

{
  first-param: 'My Name',
  colors: { ruby-red: 1, blue-fish: 3 }
}

It's great for API with request data format restrictions

Available transformers:

  • camelize
  • capitalize
  • classify
  • dasherize
  • decamelize
  • underscore

adapterOptions

Pass custom adapter options to handle them in urlForCustomAction in case of using customAction. Required usage of mixin: AdpaterMixin

responseType

You can easily observe the returned model by changing responseType to array or object according to what type of data your server will return.

When array:

model.customAction({}, { responseType: 'array' }) // returns DS.PromiseArray

When object:

model.customAction({}, { responseType: 'object' }) // returns DS.PromiseObject

When null (default):

model.customAction({}, { responseType: null }) // returns Promise

null is useful if you don't care about the response or just want to use then on the promise without using binding or display it in the template.

queryParams

You can pass a query params for a request by passing an {} with properties, eg: { include: 'owner' } ** Remember: Query params are not normalized! You have to pass it in the correct format. **

Development

Installation

  • git clone https://github.com/Exelord/ember-custom-actions.git
  • cd ember-custom-actions
  • npm install

Linting

  • npm run lint:hbs
  • npm run lint:js
  • npm run lint:js -- --fix

Running tests

  • ember test – Runs the test suite on the current Ember version
  • ember test --server – Runs the test suite in "watch mode"
  • ember try:each – Runs the test suite against multiple Ember versions

Running the dummy application

For more information on using ember-cli, visit https://ember-cli.com/.

Thanks

Big thanks to Mike North and his Project for the initial concept.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/exelord/ember-custom-actions. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

This version of the package is available as open source under the terms of the MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].