Skip to content

Commit

Permalink
feat(createAction): add parameter payloadCreator, metaCreators (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
hitmands committed Jan 24, 2018
1 parent 0c19233 commit ea1f39c
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
2 changes: 1 addition & 1 deletion index.d.ts
Expand Up @@ -17,7 +17,7 @@ declare module 'redux-fluent' {
P extends object = object,
M extends object = object,
T extends string = string
>(type: T): I.ActionCreator<P, M, T>;
>(type: T, payloadCreator?: (p: any) => P, metaCreator?: (m: any) => M): I.ActionCreator<P, M, T>;
}

declare namespace /* Interfaces */ I {
Expand Down
13 changes: 9 additions & 4 deletions src/Action/Action.js
@@ -1,11 +1,16 @@
export default function ActionCreatorFactory(type) {
function actionCreator(payload, meta) {
const identity = arg => arg;

export default function ActionCreatorFactory(type, payloadCreator, metaCreator) {
function actionCreator(rawPayload, rawMeta) {
const action = Object.create(null);

const payload = (payloadCreator || identity)(rawPayload) || null;
const meta = (metaCreator || identity)(rawMeta) || null;

action.type = type;
action.error = payload instanceof Error;
action.meta = meta || null;
action.payload = payload || null;
action.meta = meta;
action.payload = payload;

return Object.freeze(action);
}
Expand Down
22 changes: 22 additions & 0 deletions src/Action/Action.spec.js
Expand Up @@ -9,6 +9,28 @@ describe('createAction', () => {
expect(createAction('test')).toEqual(jasmine.any(Function));
});

it('Factory should accept a payloadCreator', () => {
const payloadCreator = jasmine.createSpy('payloadCreator')
.and.callFake(todoId => ({ id: todoId }));

const deleteTodo = createAction('@@todos/:id | delete', payloadCreator);
const todoId = 12;

expect(deleteTodo(todoId).payload).toEqual({ id: todoId });
expect(payloadCreator).toHaveBeenCalledWith(todoId);
});

it('Factory should accept a metaCreator', () => {
const metaCreator = jasmine.createSpy('metaCreator')
.and.callFake(metaThing => ({ id: metaThing }));

const deleteTodo = createAction('@@todos/:id | delete', null, metaCreator);
const metaThing = 'Hello World';

expect(deleteTodo(null, metaThing).meta).toEqual({ id: metaThing });
expect(metaCreator).toHaveBeenCalledWith(metaThing);
});

describe('actionCreator', () => {
it('should have a property type', () => {
expect(createAction(type)).toHaveProperty('type', type);
Expand Down

0 comments on commit ea1f39c

Please sign in to comment.