Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,27 @@ export default DS.Model.extend({

*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`](https://github.com/mike-north/ember-api-actions/blob/master/addon/utils/serialize-and-push.ts) for an example.

### ES Class Support

Decorators are also provided for `memberAction` and `collectionAction` for usage with ES classes rather than the classic Ember classes. The same configuration options are supported:

```javascript
import Model, { attr } from '@ember-data/model';
import { memberAction, collectionAction } from 'ember-api-actions/decorators';

export default class FruidModel extends Model {
@attr('string') name;
// /fruits/123/ripen
@memberAction({ path: 'ripen' }) ripen;
// /fruits/citrus
@collectionAction({
path: 'citrus',
type: 'post', // HTTP POST request
urlType: 'findRecord' // Base of the URL that's generated for the action
}) getAllCitrus;
}
```

## Customization

ember-api-actions generates URLs and ajax configuration via ember-data adapters. It will identify the appropriate adapter, and call the `buildURL` and `ajaxOptions` methods to send a JSON request similar to way conventional ember-data usage works.
Expand Down
19 changes: 19 additions & 0 deletions addon/decorators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import collectionOp, { CollectionOperationOptions } from './utils/collection-action';
import instanceOp, { InstanceOperationOptions } from './utils/member-action';

export function collectionAction<IN = any, OUT = any>(options: CollectionOperationOptions<IN, OUT>) {
return function createCollectionActionDescriptor(target: any, propertyName: string): any {
return {
value: collectionOp(options)
};
}
}

export function memberAction<IN = any, OUT = any>(options: InstanceOperationOptions<IN, OUT>) {
return function createMemberActionDescriptor(target: any, propertyName: string): any {
return {
value: instanceOp(options)
};
}
}

3 changes: 1 addition & 2 deletions addon/utils/collection-action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { assign } from '@ember/polyfills';
import Model from 'ember-data/model';
import { Value as JSONValue } from 'json-typescript';
import { _getModelClass, _getModelName, _getStoreFromRecord, buildOperationUrl } from './build-url';
Expand All @@ -25,7 +24,7 @@ export default function collectionOp<IN = any, OUT = any>(options: CollectionOpe
const fullUrl = buildOperationUrl(model, options.path, urlType, false);
const data = (options.before && options.before.call(model, payload)) || payload;
return adapter
.ajax(fullUrl, requestType, assign(options.ajaxOptions || {}, { data }))
.ajax(fullUrl, requestType, Object.assign(options.ajaxOptions || {}, { data }))
.then((response: JSONValue) => {
if (options.after && !model.isDestroyed) {
return options.after.call(model, response);
Expand Down
3 changes: 1 addition & 2 deletions addon/utils/member-action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { assign } from '@ember/polyfills';
import Model from 'ember-data/model';
import { Value as JSONValue } from 'json-typescript';
import { _getModelClass, _getModelName, _getStoreFromRecord, buildOperationUrl } from './build-url';
Expand All @@ -23,7 +22,7 @@ export default function instanceOp<IN = any, OUT = any>(options: InstanceOperati
const adapter = store.adapterFor(modelName);
const fullUrl = buildOperationUrl(this, path, urlType);
const data = (before && before.call(this, payload)) || payload;
return adapter.ajax(fullUrl, requestType, assign(ajaxOptions || {}, { data })).then((response: JSONValue) => {
return adapter.ajax(fullUrl, requestType, Object.assign(ajaxOptions || {}, { data })).then((response: JSONValue) => {
if (after && !this.isDestroyed) {
return after.call(this, response);
}
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@
"typescript": "4.2.4"
},
"engines": {
"node": "10.* || >= 12.*"
"node": "16.* || >= 18.*"
},
"ember-addon": {
"configPath": "tests/dummy/config",
Expand All @@ -97,7 +97,7 @@
"extends": "@mike-north/js-lib-semantic-release-config"
},
"volta": {
"node": "12.22.2",
"node": "18.17.1",
"yarn": "1.22.10"
}
}
3 changes: 1 addition & 2 deletions tests/dummy/app/models/fruit.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
// BEGIN-SNIPPET fruit-model
import { assign } from '@ember/polyfills';
import { collectionAction, memberAction, serializeAndPush } from 'ember-api-actions';
import DS from 'ember-data';

const { attr, Model } = DS;

function mergeAttributes(attributes) {
const payload = this.serialize();
payload.data.attributes = assign(payload.data.attributes || {}, attributes);
payload.data.attributes = Object.assign(payload.data.attributes || {}, attributes);
return payload;
}
const Fruit = Model.extend({
Expand Down
51 changes: 51 additions & 0 deletions tests/unit/utils/decorators/collection-action-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { collectionAction } from 'ember-api-actions/decorators';
import DS from 'ember-data';
import { setupTest } from 'ember-qunit';
import { TestContext } from 'ember-test-helpers';
import { module, test } from 'qunit';
import setupPretender from '../../../helpers/setup-pretender';

const { Model, attr } = DS;

class Fruit extends Model {
@attr('string')
public name?: string;

@collectionAction({ path: 'ripenEverything' })
public ripenAll: any;
}

module('Unit | Utility | decorators/collection-action', (hooks) => {
setupTest(hooks);
setupPretender(hooks);

let fruit: Fruit;

hooks.beforeEach(function(this: TestContext) {
this.owner.unregister('model:fruit');
this.owner.register('model:fruit', Fruit);

this.store = this.owner.lookup('service:store');

fruit = this.store.createRecord('fruit', {
id: 1,
name: 'apple'
});
});

test('it adds a method through a decorator', async function(assert) {
assert.expect(3);

this.server.put('/fruits/ripenEverything', (request) => {
const data = JSON.parse(request.requestBody);
assert.deepEqual(data, { test: 'ok' }, 'collection action - request payload is correct');
return [200, {}, '{"status": "ok"}'];
});

assert.equal(typeof fruit.ripenAll, 'function', 'Assigns a method on the type');

const result = await fruit.ripenAll({ test: 'ok' });

assert.deepEqual(result, { status: 'ok' }, 'Passes through the API response');
});
});
53 changes: 53 additions & 0 deletions tests/unit/utils/decorators/member-action-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { memberAction } from 'ember-api-actions/decorators';
import DS from 'ember-data';
import { setupTest } from 'ember-qunit';
import { TestContext } from 'ember-test-helpers';
import { module, test } from 'qunit';
import setupPretender from '../../../helpers/setup-pretender';

const { Model, attr } = DS;

class Fruit extends Model {
@attr('string')
public name?: string;

@memberAction({ path: 'doRipen' })
public ripen: any;
}

module('Unit | Utility | decorators/member-action', (hooks) => {
setupTest(hooks);
setupPretender(hooks);

let fruit: Fruit;

hooks.beforeEach(function(this: TestContext) {
this.owner.unregister('model:fruit');
this.owner.register('model:fruit', Fruit);

this.store = this.owner.lookup('service:store');

fruit = this.store.createRecord('fruit', {
id: 1,
name: 'apple'
});
});

test('it adds a method through a decorator', async function(assert) {
assert.expect(4);

this.server.put('/fruits/:id/doRipen', (request) => {
const data = JSON.parse(request.requestBody);
assert.deepEqual(data, { id: '1', name: 'apple' }, 'member action - request payload is correct');
assert.equal(request.params.id, '1', 'request was made to the right ID');
return [200, {}, '{"status": "ok"}'];
});

assert.equal(typeof fruit.ripen, 'function', 'Assigns a method on the type');

const { id, name } = fruit;
const result = await fruit.ripen({ id, name });

assert.deepEqual(result, { status: 'ok' }, 'Passes through the API response');
});
});
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"allowJs": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"noEmitOnError": false,
"noImplicitAny": true,
"noImplicitThis": true,
Expand Down
Loading