Skip to content

Commit

Permalink
allow inheritted actions
Browse files Browse the repository at this point in the history
  • Loading branch information
Yifan Jiang committed Aug 24, 2019
1 parent 6c93fe9 commit 221a7dd
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
14 changes: 14 additions & 0 deletions __tests__/immer-reducer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,20 @@ afterEach(() => {
setPrefix("IMMER_REDUCER");
});

test("can detect inherited actions", () => {
class Parent extends ImmerReducer<any> {
setFoo(foo: string) {}
}

class Child extends Parent {
setFoo2(foo: string) {}
}

const actions = createActionCreators(Child);
expect(actions.setFoo).toBeTruthy();
expect(actions.setFoo2).toBeTruthy();
});

test("can create reducers", () => {
const initialState = {foo: "bar"};

Expand Down
13 changes: 9 additions & 4 deletions src/immer-reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,18 +268,23 @@ function getArgsFromImmerAction(action: ImmerAction): unknown[] {
return [action.payload];
}

function getAllPropertyNames (obj: object) {
const proto = Object.getPrototypeOf(obj);
const inherited: string[] = (proto) ? getAllPropertyNames(proto) : [];
return Array.from(new Set(Object.getOwnPropertyNames(obj).concat(inherited)));
}

export function createActionCreators<T extends ImmerReducerClass>(
immerReducerClass: T,
): ActionCreators<T> {
setCustomNameForDuplicates(immerReducerClass);

const actionCreators: {[key: string]: Function} = {};

Object.getOwnPropertyNames(immerReducerClass.prototype).forEach(key => {
if (key === "constructor") {
const immerReducerProperties = getAllPropertyNames(ImmerReducer.prototype);
getAllPropertyNames(immerReducerClass.prototype).forEach(key => {
if (immerReducerProperties.includes(key)) {
return;
}

const method = immerReducerClass.prototype[key];

if (typeof method !== "function") {
Expand Down

0 comments on commit 221a7dd

Please sign in to comment.