Skip to main content

The Repository Pattern

One way to use Elf is following the Repository Design Pattern. Implementing the Repository pattern is relatively simple. It's a file that encapsulates the store queries and mutations:

auth.repository.ts
import { createStore, withProps, select } from '@ngneat/elf';

interface AuthProps {
user: { id: string } | null;
}

const authStore = createStore(
{ name: 'auth' },
withProps<AuthProps>({ user: null })
);

export const user$ = authStore.pipe(select((state) => state.user));

export function updateUser(user: AuthProps['user']) {
authStore.update((state) => ({
...state,
user,
}));
}

The Repository pattern provides 2 main benefits:

  1. Using the pattern, you can replace your data store without changing your business code.
  2. It encourages you to implement all store operations in one place, making your code more reusable and easy to find.

You can also use the object-oriented programming (OOP) approach:

auth.repository.ts
import { createStore, withProps, select } from '@ngneat/elf';

interface AuthProps {
user: { id: string } | null;
}

const authStore = createStore(
{ name: 'auth' },
withProps<AuthProps>({ user: null })
);

export class AuthRepository {
user$ = authStore.pipe(select((state) => state.user));

updateUser(user: AuthProps['user']) {
authStore.update((state) => ({
...state,
user,
}));
}
}

Creating a Repository with the CLI

Elf comes with a CLI that'll generate a repository with all the features you need. Check out the docs for more information.