Skip to content

Allow Entity id to be either a number or a string #29

Description

@cam-m

Hi Michael,

Thanks for building this library, its been very useful so far.

Would it be possible to add support for entities that identifiers of type number?

E.g.

export class SomeEntity {
  SomeEntityId: number;
  otherEntities: AnotherEntity[]'
}

export class AnotherEntity {
  AnotherEntityId: number;
}

export someEntitySchema = new schema.Entity(
  'SomeEntity', 
  {
    otherEntities: [anotherEntitySchema]
  }, 
  {
    idAttribute: 'SomeEntityId'
  });
export anotherEntitySchema = new schema.Entity('AnotherEntity', {}, idAttribute: 'AnotherEntityId'});

Mostly this already works fine, except that I can't use the provided entityProjecter which throws a typescript error:

Argument of type '(entities: {}, id: string) => SomeEntity' is not assignable to parameter of type '(s1: {}, s2: number)

Normalizr itself seems to support ids being numbers and strings, so I modified the interfaces in ngrx-normalizr/normalize.d.ts to allow for numbers and this works (for me at least):

import { MemoizedSelector } from '@ngrx/store';
import { schema } from 'normalizr';
export interface EntityMap {
    [key: string]: {
        [id: string]: any;
        [id: number]: any;
    };
}
export interface NormalizedState {
    normalized: NormalizedEntityState;
}
export interface NormalizedEntityState {
    result: string[];
    entities: EntityMap;
}
export declare function normalized(state: NormalizedEntityState, action: any): {
    result: any;
    entities: any;
};
export declare const getNormalizedEntities: MemoizedSelector<any, EntityMap>;
export declare const getResult: MemoizedSelector<any, any[]>;
export interface SchemaSelectors<T> {
    getNormalizedEntities: MemoizedSelector<any, EntityMap>;
    getEntities: MemoizedSelector<{}, T[]>;
    entityProjector: (entities: {}, id: string | number) => T;
    entitiesProjector: (entities: {}) => T[];
}
export declare function createSchemaSelectors<T>(schema: schema.Entity): SchemaSelectors<T>;

I can create a pull request for you if you prefer, but I had trouble getting the karma tests to run... so thought I'd just ask in case this would be a simple change for you.

Thanks again,

Cam

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions