ngrx / platform

Reactive State for Angular
https://ngrx.io
Other
7.96k stars 1.95k forks source link

`@ngrx/signals/entity`: Introduce `entityConfig` function #4393

Closed markostanimirovic closed 1 week ago

markostanimirovic commented 3 weeks ago

Which @ngrx/* package(s) are relevant/related to the feature request?

signals

Information

To use @ngrx/signals/entities plugin with custom configuration, we usually repeat the same properties multiple times:

const selectTodoId = (todo: Todo) => todo._id;

const TodosStore = signalStore(
  withEntities({ entity: type<Todo>(), collection: 'todo' }),
  withMethods((store) => ({
    addTodo(todo: Todo): void {
      patchState(
        store,
        addEntity(todo, { collection: 'todo', selectId: selectTodoId })
      );
    },
    setTodos(todo: Todo[]): void {
      patchState(
        store,
        setEntities(todo, { collection: 'todo', selectId: selectTodoId })
      );
    },
  })
);

With the entityConfig function, the same store will look like this:

const todoConfig = entityConfig({
  entity: type<Todo>(),
  collection: 'todo',
  selectId: (todo) => todo._id,
});

const TodosStore = signalStore(
  withEntities(todoConfig),
  withMethods((store) => ({
    addTodo(todo: Todo): void {
      patchState(store, addEntity(todo, todoConfig));
    },
    setTodos(todo: Todo[]): void {
      patchState(store, setEntities(todo, todoConfig));
    },
  })
);

Describe any alternatives/workarounds you're currently using

The todoConfig object can be defined as follows:

const todoConfig = {
  entity: type<Todo>(),
  collection: 'todo',
  selectId: (todo) => todo._id,
} as const;

However, with dedicated function, type safety will be ensured.

I would be willing to submit a PR to fix this issue