Skip to content
Merged
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
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;
};
}