Skip to content

Commit

Permalink
Merge pull request #8 from acdlite/create-action-meta
Browse files Browse the repository at this point in the history
Allow to fill `meta` prop of an action
  • Loading branch information
acdlite committed Jul 13, 2015
2 parents 21cac4a + 0b82c83 commit 8684815
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
30 changes: 26 additions & 4 deletions src/__tests__/createAction-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,52 @@ import isPlainObject from 'lodash.isplainobject';
describe('createAction()', () => {
describe('resulting action creator', () => {
const type = 'TYPE';
const actionCreator = createAction(type, b => b);
const foobar = { foo: 'bar' };
const action = actionCreator(foobar);

it('returns plain object', () => {
const actionCreator = createAction(type, b => b);
const foobar = { foo: 'bar' };
const action = actionCreator(foobar);
expect(isPlainObject(action)).to.be.true;
});

it('uses return value as payload', () => {
const actionCreator = createAction(type, b => b);
const foobar = { foo: 'bar' };
const action = actionCreator(foobar);
expect(action.payload).to.equal(foobar);
});

it('has no extraneous keys', () => {
const actionCreator = createAction(type, b => b);
const foobar = { foo: 'bar' };
const action = actionCreator(foobar);
expect(action).to.deep.equal({
type,
payload: foobar
});
});

it('uses identity function if actionCreator is not a function', () => {
expect(createAction(type)(foobar)).to.deep.equal({
const actionCreator = createAction(type);
const foobar = { foo: 'bar' };
const action = actionCreator(foobar);
expect(action).to.deep.equal({
type,
payload: foobar
});
});

it('accepts a second parameter for adding meta to object', () => {
const actionCreator = createAction(type, null, ({ cid }) => ({ cid }));
const foobar = { foo: 'bar', cid: 5 };
const action = actionCreator(foobar);
expect(action).to.deep.equal({
type,
payload: foobar,
meta: {
cid: 5
}
});
});
});
});
16 changes: 11 additions & 5 deletions src/createAction.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@ function identity(t) {
return t;
}

export default function createAction(type, actionCreator) {
export default function createAction(type, actionCreator, metaCreator) {
const finalActionCreator = typeof actionCreator === 'function'
? actionCreator
: identity;

return (...args) => ({
type,
payload: finalActionCreator(...args)
});
return (...args) => {
const action = {
type,
payload: finalActionCreator(...args)
};

if (typeof metaCreator === 'function') action.meta = metaCreator(...args);

return action;
};
}

0 comments on commit 8684815

Please sign in to comment.