Skip to content

Commit

Permalink
feat(signals): new callWith prop for withCalls, and defaultResult pro…
Browse files Browse the repository at this point in the history
…p to initialize result

new callWithParams prop allows reactively call the method when other signals or observables change

Fix #151
  • Loading branch information
Gabriel Guerrero committed Jan 25, 2025
1 parent 774d69d commit 78fd8fa
Show file tree
Hide file tree
Showing 7 changed files with 798 additions and 55 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { inject } from '@angular/core';
import { computed, effect, inject } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import {
typedCallConfig,
withCalls,
withCallStatus,
withEntitiesLoadingCall,
Expand All @@ -9,11 +11,11 @@ import {
withEntitiesSingleSelection,
withEntitiesSyncToRouteQueryParams,
} from '@ngrx-traits/signals';
import { signalStore, type } from '@ngrx/signals';
import { withEntities } from '@ngrx/signals/entities';
import { patchState, signalStore, type, withHooks } from '@ngrx/signals';
import { setEntities, withEntities } from '@ngrx/signals/entities';
import { map } from 'rxjs/operators';

import { Product } from '../../models';
import { Product, ProductDetail } from '../../models';
import { OrderService } from '../../services/order.service';
import { ProductService } from '../../services/product.service';

Expand Down Expand Up @@ -54,21 +56,35 @@ export const ProductsLocalStore = signalStore(
.pipe(map((d) => d.resultList));
},
}),
withCalls(() => ({
loadProductDetail: {
withCalls(({ productsEntitySelected }) => ({
loadProductDetail: typedCallConfig({
call: ({ id }: { id: string }) =>
inject(ProductService).getProductDetail(id),
resultProp: 'productDetail',
mapPipe: 'switchMap',
},
// call load the product detail when a product is selected
callWith: productsEntitySelected,
// productsEntitySelected is of type Signal<Product | undefined> so it can be pass directly to callWith
// because it matches the type the call parameter, but you can use a function as bellow if it doesnt
// callWith: () =>
// productsEntitySelected()
// ? { id: productsEntitySelected()!.id }
// : undefined, // if no product is selected, skip call
}),
checkout: () => inject(OrderService).checkout(),
})),
// loadProductDetail callWith is equivalent to:
// withHooks((store) => {
// return {
// onInit() {
// toObservable(store.productsEntitySelected)
// .pipe(filter((v) => !!v))
// .subscribe((v) => {
// store.loadProductDetail({ id: v!.id });
// });
// };
// }),
withEntitiesSyncToRouteQueryParams({
collection,
entity,
onQueryParamsLoaded: ({ productsEntitySelected, loadProductDetail }) => {
if (productsEntitySelected())
loadProductDetail(productsEntitySelected()!);
},
}),
);
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,29 @@ import {
} from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { withCalls, withRouteParams } from '@ngrx-traits/signals';
import {
typedCallConfig,
withCalls,
withRouteParams,
} from '@ngrx-traits/signals';
import { signalStore, withHooks } from '@ngrx/signals';

import { ProductService } from '../../services/product.service';

const ProductDetailStore = signalStore(
withRouteParams(({ id }) => ({ id })),
withCalls(() => ({
loadProductDetail: (id: string) =>
inject(ProductService).getProductDetail(id),
})),
withHooks(({ loadProductDetail, id }) => ({
onInit: () => {
loadProductDetail(id());
},
withRouteParams(({ id }) => ({ id: id as string })),
withCalls(({ id }) => ({
loadProductDetail: typedCallConfig({
call: (id: string) => inject(ProductService).getProductDetail(id),
callWith: id(),
}),
})),
// This is the same as the above withCalls
// withHooks(({ loadProductDetail, id }) => ({
// onInit: () => {
// loadProductDetail(id());
// },
// })),
);
@Component({
selector: 'route-product-detail',
Expand All @@ -39,26 +46,19 @@ const ProductDetailStore = signalStore(
imports: [MatCardModule, MatProgressSpinnerModule, CurrencyPipe],
providers: [ProductDetailStore],
template: `
@if (store.isLoadProductDetailLoaded()) {
@if (store.loadProductDetailResult(); as result) {
<mat-card>
<mat-card-header>
<mat-card-title>{{
store.loadProductDetailResult()?.name
}}</mat-card-title>
<mat-card-title>{{ result.name }}</mat-card-title>
<mat-card-subtitle
>Price: £{{ store.loadProductDetailResult()?.price | currency }}
>Price: £{{ result.price | currency }}
Released:
{{
store.loadProductDetailResult()?.releaseDate
}}</mat-card-subtitle
{{ result.releaseDate }}</mat-card-subtitle
>
</mat-card-header>
<img
mat-card-image
src="/{{ store.loadProductDetailResult()?.image }}"
/>
<img mat-card-image src="/{{ result.image }}" />
<mat-card-content>
<p>{{ store.loadProductDetailResult()?.description }}</p>
<p>{{ result.description }}</p>
</mat-card-content>
</mat-card>
} @else if (store.isLoadProductDetailLoading()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import { ProductsLocalStore } from './product.store';
<!-- [selectedSort]="store.productsSort()" -->
<mat-paginator
[pageSizeOptions]="[5, 10, 25, 100]"
[length]="store.productsCurrentPage().total"
[length]="store.productsCurrentPage.total()"
[pageSize]="store.productsCurrentPage().pageSize"
[pageIndex]="store.productsCurrentPage().pageIndex"
(page)="store.loadProductsPage($event)"
Expand Down Expand Up @@ -109,7 +109,6 @@ export class SignalProductListPaginatedPageContainerComponent {

select({ id }: Product) {
this.store.selectProductsEntity({ id });
this.store.loadProductDetail({ id });
}

checkout() {
Expand Down
3 changes: 3 additions & 0 deletions libs/ngrx-traits/signals/src/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ export function toMap(a: Array<string | number>) {
return acum;
}, {});
}
export function insertIf<T>(condition: any, getElement: () => T): [T] {
return (condition ? [getElement()] : []) as [T];
}
78 changes: 73 additions & 5 deletions libs/ngrx-traits/signals/src/lib/with-calls/with-calls.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,86 @@ export type CallConfig<
Result = any,
PropName extends string = string,
Error = any,
DefaultResult = any,
> = {
/**
* The main function to be called.
*/
call: Call<Param, Result>;

/**
* The name of the property where the result of the call will be stored.
*/
resultProp: PropName;

/**
* Specifies how to map emissions of the call, using one of the following:
* - 'switchMap': Cancels the previous call when a new one starts.
* - 'concatMap': Queues calls and executes them sequentially.
* - 'exhaustMap': Ignores new calls until the current one completes.
* Default is exhaustMap
*/
mapPipe?: 'switchMap' | 'concatMap' | 'exhaustMap';

/**
* default is true, if false disables automatically storing the result of the
* function, and removes the generated types.
*/
storeResult?: boolean;
onSuccess?: (result: Result, param: Param) => void;
mapError?: (error: unknown, param: Param) => Error;
onError?: (error: Error, param: Param) => void;

/**
* A default value for the result, used if the call produces no result.
*/
defaultResult?: NoInfer<DefaultResult>;

/**
* Callback function invoked on successful completion of the call.
* Receives the result of the call and the parameter used.
*/
onSuccess?: (result: NoInfer<Result>, param: NoInfer<Param>) => void;

/**
* A function to transform an error from the call into a custom `Error` type.
* Receives the error and the parameter used.
*/
mapError?: (error: unknown, param: NoInfer<Param>) => Error;

/**
* Callback function invoked if the call encounters an error.
* Receives the mapped error and the parameter used.
*/
onError?: (error: Error, param: NoInfer<Param>) => void;

/**
* A function with condition that determines whether the call should be skipped.
* The function accepts the call parameter and must return a boolean | Signal<boolean> | Observable<boolean>.
*/
skipWhen?:
| Call<Param, boolean>
| Call<NoInfer<Param>, boolean>
| (() => boolean)
| ((param: Param) => boolean);
| ((param: NoInfer<Param>) => boolean);

/**
* Reactively execute the call with the provided params.
* Supports the following:
* - A direct parameter value. Which execute the call once on init.
* - A `Signal` or `Observable` emitting the parameter of the call or undefined.
* - A function returning the parameter or undefined.
*
* **Warning**: By default, when withCall is a function, signal
* or observable that when returns a falsy value it will skip the call.
* To override this behavior, define a skipWhen with your own rule or skipWhen: () => false
* to always execute on any value.
*/
callWith?: Param extends Record<string, any> | string | number | boolean
?
| NoInfer<Param>
| null
| undefined
| Signal<NoInfer<Param | null | undefined>>
| Observable<NoInfer<Param | null | undefined>>
| (() => NoInfer<Param> | null | undefined)
: Signal<boolean> | Observable<boolean> | (() => boolean) | boolean;
};

export type ExtractCallResultType<T extends Call | CallConfig> =
Expand Down
Loading

0 comments on commit 78fd8fa

Please sign in to comment.