Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(signals): add enabled function to withCalls config #135

Merged
merged 1 commit into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ export type CallConfig<
onSuccess?: (result: Result, param: Param) => void;
mapError?: (error: unknown, param: Param) => Error;
onError?: (error: Error, param: Param) => void;
skipWhen?:
| Call<Param, boolean>
| (() => boolean)
| ((param: Param) => boolean);
};

export type ExtractCallResultType<T extends Call | CallConfig> =
T extends Call<any, infer R>
? R
Expand Down
162 changes: 161 additions & 1 deletion libs/ngrx-traits/signals/src/lib/with-calls/with-calls.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { patchState, signalStore, withState } from '@ngrx/signals';
import { BehaviorSubject, Subject, tap, throwError } from 'rxjs';
import { BehaviorSubject, of, Subject, tap, throwError } from 'rxjs';

import { typedCallConfig, withCalls } from '../index';

Expand Down Expand Up @@ -507,4 +507,164 @@ describe('withCalls', () => {
expect(consoleWarn).not.toHaveBeenCalledTimes(1);
});
});
describe('skipWhen function', () => {
it('returning true in skipWhen should skip call ', async () => {
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {
/* Empty */
});
TestBed.runInInjectionContext(async () => {
const Store = signalStore(
withCalls(() => ({
testCall: typedCallConfig({
call: () => apiResponse,
mapPipe: 'exhaustMap',
skipWhen: () => true,
}),
})),
);
const store = new Store();
expect(store.isTestCallLoading()).toBeFalsy();

store.testCall();
expect(store.isTestCallLoading()).toBeFalsy();
apiResponse.next('test');
expect(store.isTestCallLoaded()).toBeFalsy();
expect(store.testCallResult()).toBeUndefined();
expect(store.testCallCallStatus()).toEqual('init');
expect(consoleWarn).toHaveBeenCalledWith('Call testCall is skip');
});
});

it('returning false in skipWhen should make call ', async () => {
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {
/* Empty */
});
TestBed.runInInjectionContext(async () => {
const Store = signalStore(
withCalls(() => ({
testCall: typedCallConfig({
call: () => apiResponse,
mapPipe: 'exhaustMap',
skipWhen: () => false,
}),
})),
);
const store = new Store();
expect(store.isTestCallLoading()).toBeFalsy();

store.testCall();
expect(store.isTestCallLoading()).toBeTruthy();
apiResponse.next('test');
expect(store.isTestCallLoaded()).toBeTruthy();
expect(store.testCallResult()).toEqual('test');
expect(consoleWarn).not.toHaveBeenCalled();
});
});

it('returning an Observable with true in skipWhen should skip call', async () => {
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {
/* Empty */
});
TestBed.runInInjectionContext(async () => {
const Store = signalStore(
withCalls(() => ({
testCall: typedCallConfig({
call: () => apiResponse,
mapPipe: 'exhaustMap',
skipWhen: () => of(true),
}),
})),
);
const store = new Store();
expect(store.isTestCallLoading()).toBeFalsy();

store.testCall();
expect(store.isTestCallLoading()).toBeFalsy();
apiResponse.next('test');
expect(store.isTestCallLoaded()).toBeFalsy();
expect(store.testCallResult()).toBeUndefined();
expect(store.testCallCallStatus()).toEqual('init');
expect(consoleWarn).toHaveBeenCalledWith('Call testCall is skip');
});
});

it('returning an Observable with false in skipWhen should run call', async () => {
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {
/* Empty */
});
TestBed.runInInjectionContext(async () => {
const Store = signalStore(
withCalls(() => ({
testCall: typedCallConfig({
call: () => apiResponse,
mapPipe: 'exhaustMap',
skipWhen: () => of(false),
}),
})),
);
const store = new Store();
expect(store.isTestCallLoading()).toBeFalsy();

store.testCall();
expect(store.isTestCallLoading()).toBeTruthy();
apiResponse.next('test');
expect(store.isTestCallLoaded()).toBeTruthy();
expect(store.testCallResult()).toEqual('test');
expect(consoleWarn).not.toHaveBeenCalled();
});
});

it('returning a Promise with true in skipWhen should skip call', async () => {
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {
/* Empty */
});
TestBed.runInInjectionContext(async () => {
const Store = signalStore(
withCalls(() => ({
testCall: typedCallConfig({
call: () => apiResponse,
mapPipe: 'exhaustMap',
skipWhen: () => Promise.resolve(true),
}),
})),
);
const store = new Store();
expect(store.isTestCallLoading()).toBeFalsy();

store.testCall();
expect(store.isTestCallLoading()).toBeFalsy();
apiResponse.next('test');
expect(store.isTestCallLoaded()).toBeFalsy();
expect(store.testCallResult()).toBeUndefined();
expect(store.testCallCallStatus()).toEqual('init');
expect(consoleWarn).toHaveBeenCalledWith('Call testCall is skip');
});
});

it('returning a Promise with false in skipWhen should run call', async () => {
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {
/* Empty */
});
TestBed.runInInjectionContext(async () => {
const Store = signalStore(
withCalls(() => ({
testCall: typedCallConfig({
call: () => apiResponse,
mapPipe: 'exhaustMap',
skipWhen: () => Promise.resolve(false),
}),
})),
);
const store = new Store();
expect(store.isTestCallLoading()).toBeFalsy();

store.testCall();
expect(store.isTestCallLoading()).toBeTruthy();
apiResponse.next('test');
expect(store.isTestCallLoaded()).toBeTruthy();
expect(store.testCallResult()).toEqual('test');
expect(consoleWarn).not.toHaveBeenCalled();
});
});
});
});
92 changes: 57 additions & 35 deletions libs/ngrx-traits/signals/src/lib/with-calls/with-calls.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
computed,
DestroyRef,
EnvironmentInjector,
inject,
isDevMode,
Expand All @@ -10,22 +9,20 @@ import {
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
patchState,
Prettify,
signalStoreFeature,
SignalStoreFeature,
SignalStoreFeatureResult,
StateSignals,
withComputed,
withMethods,
withState,
WritableStateSource,
} from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import {
catchError,
concatMap,
exhaustMap,
finalize,
first,
from,
ignoreElements,
map,
Expand All @@ -41,6 +38,7 @@ import {
tap,
timer,
} from 'rxjs';
import { filter } from 'rxjs/operators';

import {
CallStatus,
Expand Down Expand Up @@ -85,6 +83,10 @@ import { getWithCallKeys } from './with-calls.util';
* onError: (error, callParam) => {
* // do something with the error
* },
* skipWhen: (callParam) => {
* // if return true, the call will be skip, if false, the call will execute as usual
* return // boolean | Promise<boolean> | Observable<boolean>
* },
* }),
* checkout: () =>
* inject(OrderService).checkout({
Expand Down Expand Up @@ -229,41 +231,61 @@ export function withCalls<
} as any);

const callFn = getCallFn(callName, call);
const skipWhenFn =
(isCallConfig(call) && call.skipWhen) || undefined;

acc[callNameKey] = rxMethod<unknown[]>(
pipe(
mapPipe((params) => {
setLoading();
return runInInjectionContext(environmentInjector, () => {
return callFn(params).pipe(
map((result) => {
if (
!isCallConfig(call) ||
call.storeResult !== false
) {
patchState(state, {
[resultPropKey]: result,
});
}
setLoaded();
isCallConfig(call) &&
call.onSuccess &&
call.onSuccess(result, params);
}),
takeUntilDestroyed(),
catchError((error: unknown) => {
const e =
(isCallConfig(call) &&
call.mapError?.(error, params)) ||
error;
setError(e);
isCallConfig(call) &&
call.onError &&
call.onError(e, params);
return of();
}),
);
concatMap((params) => {
const skip = skipWhenFn?.(params) ?? false;
const process$ = mapPipe((params) => {
setLoading();
return runInInjectionContext(environmentInjector, () => {
return callFn(params).pipe(
map((result) => {
if (
!isCallConfig(call) ||
call.storeResult !== false
) {
patchState(state, {
[resultPropKey]: result,
});
}
setLoaded();
isCallConfig(call) &&
call.onSuccess &&
call.onSuccess(result, params);
}),
takeUntilDestroyed(),
catchError((error: unknown) => {
const e =
(isCallConfig(call) &&
call.mapError?.(error, params)) ||
error;
setError(e);
isCallConfig(call) &&
call.onError &&
call.onError(e, params);
return of();
}),
);
});
});
if (typeof skip === 'boolean') {
if(isDevMode() && skip)
console.warn(`Call ${callName} is skip`)
return skip ? of() : of(params).pipe(process$);
}
// skip is a promise or observable
return from(skip).pipe(
tap((value) => {
if(isDevMode() && value)
console.warn(`Call ${callName} is skip`)
}),
first((v) => v),
map(() => params),
process$,
);
}),
),
);
Expand Down