rxjs#EMPTY TypeScript Examples
The following examples show how to use
rxjs#EMPTY.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: auth.service.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
/**
* Authenticate user on backend.
* @param address wallet address
* @param nonce nonce to sign
* @param signature signed nonce
* @param walletProvider wallet provider
* @return Authentication key.
*/
private sendSignedNonce(
address: string,
nonce: string,
signature: string,
walletProvider: WALLET_NAME
): Promise<void> {
return this.httpService
.post('auth/wallets/login/', {
address,
message: nonce,
signedMessage: signature,
walletProvider,
type: this.walletConnectorService.provider.walletType.toLowerCase()
})
.pipe(switchMap(() => EMPTY))
.toPromise();
}
Example #2
Source File: index.ts From dbm with Apache License 2.0 | 6 votes |
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Resolve a pattern
*
* @param pattern - Pattern
* @param options - Options
*
* @returns File observable
*/
export function resolve(
pattern: string, options?: ResolveOptions
): Observable<string> {
return from(glob(pattern, options))
.pipe(
catchError(() => EMPTY),
switchMap(files => from(files)),
options?.watch
? mergeWith(watch(pattern, options))
: identity
)
}
Example #3
Source File: scanned-item-manager.service.ts From pantry_party with Apache License 2.0 | 6 votes |
perfomSave(item: ReadyScannedItem) {
this.updateScannedItemWithoutVersionBump(
item.barcode,
{saveInProgress: true}
);
const lastUndoKey = this.pvtUndoKey[item.barcode];
const undo$ = lastUndoKey ? this.undoCallback(lastUndoKey) : EMPTY;
concat(
undo$.pipe(
map(() => delete this.pvtUndoKey[item.barcode])
),
this.saveCallback(item).pipe(
map(r => {
this.pvtUndoKey[item.barcode] = r;
this.updateScannedItemWithoutVersionBump(
item.barcode,
{ lastSavedVersion: item.currentVersion }
);
})
)
).pipe(
takeUntil(this.ngUnsubscribe),
finalize(() => this.updateScannedItemWithoutVersionBump(
item.barcode,
{saveInProgress: false}
)),
take(1)
).subscribe();
}
Example #4
Source File: activator-installer.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
/**
* Creates a Promise that resolves when given activators signal ready.
*/
private async waitForActivatorsToSignalReady(appSymbolicName: string, activators: Activator[], monitor: ProgressMonitor): Promise<void> {
const t0 = Date.now();
const activatorLoadTimeout = Beans.get(ApplicationRegistry).getApplication(appSymbolicName)!.activatorLoadTimeout;
const readinessPromises: Promise<void>[] = activators
.reduce((acc, activator) => acc.concat(Arrays.coerce(activator.properties.readinessTopics)), new Array<string>()) // concat readiness topics
.map(readinessTopic => {
const onReadinessTimeout = (): Observable<never> => {
Beans.get(Logger).error(`[ActivatorLoadTimeoutError] Timeout elapsed while waiting for application to signal readiness [app=${appSymbolicName}, timeout=${activatorLoadTimeout}ms, readinessTopic=${readinessTopic}].`);
return EMPTY;
};
return new Promise((resolve, reject) => {
return Beans.get(MessageClient).observe$<void>(readinessTopic)
.pipe(
first(msg => msg.headers.get(MessageHeaders.AppSymbolicName) === appSymbolicName),
activatorLoadTimeout ? timeout({first: activatorLoadTimeout, with: onReadinessTimeout}) : identity,
)
.subscribe({
error: reject,
complete: resolve,
});
});
},
);
if (!readinessPromises.length) {
monitor.done();
return;
}
await Promise.all(readinessPromises);
monitor.done();
Beans.get(Logger).info(`Activator startup of '${appSymbolicName}' took ${Date.now() - t0}ms.`);
}
Example #5
Source File: emote.component.ts From App with MIT License | 6 votes |
/**
* Bring up a dialog to rename the current emote
*/
rename(): void {
const dialogRef = this.dialog.open(EmoteRenameDialogComponent, {
data: { emote: this.emote, happening: 'Rename' },
});
dialogRef.afterClosed().pipe(
filter(data => !!data && data.name !== null),
switchMap(data => this.emote?.edit({ name: data.name }, data.reason) ?? EMPTY),
).subscribe();
}
Example #6
Source File: bind.plugin.ts From ng-event-plugins with Apache License 2.0 | 6 votes |
addEventListener(
element: HTMLElement & Record<string, Observable<unknown>>,
event: string,
): Function {
element[event] = element[event] || EMPTY;
const method = this.getMethod(element, event);
const zone$ = this.manager.getZone().onStable;
const sub = concat(
zone$.pipe(takeWhile(() => element[event] === EMPTY)),
defer(() => element[event]),
).subscribe(method);
return () => sub.unsubscribe();
}
Example #7
Source File: my-expenses.page.ts From fyle-mobile-app with MIT License | 6 votes |
setAllExpensesCountAndAmount() {
this.allExpensesStats$ = this.loadData$.pipe(
switchMap((params) => {
const queryParams = JSON.parse(JSON.stringify(params.queryParams)) || {};
queryParams.tx_report_id = queryParams.tx_report_id || 'is.null';
queryParams.tx_state = 'in.(COMPLETE,DRAFT)';
if (queryParams.corporate_credit_card_account_number) {
const cardParamsCopy = JSON.parse(JSON.stringify(queryParams.corporate_credit_card_account_number));
queryParams.or = '(corporate_credit_card_account_number.' + cardParamsCopy + ')';
delete queryParams.corporate_credit_card_account_number;
}
return this.transactionService
.getTransactionStats('count(tx_id),sum(tx_amount)', {
scalar: true,
...queryParams,
})
.pipe(
catchError((err) => EMPTY),
map((stats) => {
const count = stats[0].aggregates.find((stat) => stat.function_name === 'count(tx_id)');
const amount = stats[0].aggregates.find((stat) => stat.function_name === 'sum(tx_amount)');
return {
count: count.function_value,
amount: amount.function_value || 0,
};
})
);
})
);
}
Example #8
Source File: init.ts From ble with Apache License 2.0 | 6 votes |
loadLevelFromQueryParam: Epic = (action$, { store }) => {
const urlParams = new URLSearchParams(window.location.search);
const levelId = urlParams.get('levelId');
if (levelId && window.confirm('The saved level will be overwritten. Are you sure?')) {
return ajax(`https://assets.bombhopper.io/levels/${levelId}.json`).pipe(
pluck('response'),
tap((level) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { top, right, bottom, left } = getBounds((level as any).entities);
const middle = {
x: left + (right - left) / 2,
y: top + (bottom - top) / 2,
};
applySnapshot(store.level, level);
store.editor.position.set(middle.x, middle.y);
}),
ignoreElements(),
);
}
return EMPTY;
}
Example #9
Source File: auth.service.ts From nestjs-rest-sample with GNU General Public License v3.0 | 6 votes |
validateUser(username: string, pass: string): Observable<UserPrincipal> {
return this.userService.findByUsername(username).pipe(
//if user is not found, convert it into an EMPTY.
mergeMap((p) => (p ? of(p) : EMPTY)),
// Using a general message in the authentication progress is more reasonable.
// Concise info could be considered for security.
// Detailed info will be helpful for crackers.
// throwIfEmpty(() => new NotFoundException(`username:${username} was not found`)),
throwIfEmpty(() => new UnauthorizedException(`username or password is not matched`)),
mergeMap((user) => {
const { _id, password, username, email, roles } = user;
return user.comparePassword(pass).pipe(map(m => {
if (m) {
return { id: _id, username, email, roles } as UserPrincipal;
}else {
// The same reason above.
//throw new UnauthorizedException('password was not matched.')
throw new UnauthorizedException('username or password is not matched')
}
}))
})
);
}
Example #10
Source File: UWebSocketAdapter.ts From nestjs-uws with MIT License | 6 votes |
bindMessageHandler(
buffer: { message: ArrayBuffer, isBinary: boolean },
handlers: MessageMappingProperties[],
process: (data: any) => Observable<any>,
): Observable<any> {
const stringMessageData = Buffer.from(buffer.message).toString('utf-8');
const message = JSON.parse(stringMessageData);
const messageHandler = handlers.find(
handler => handler.message === message.event,
);
if (!messageHandler) {
return EMPTY;
}
return process(messageHandler.callback(message.data));
}
Example #11
Source File: service.base.ts From litefy with MIT License | 6 votes |
Put<Tretorno>(url, model) {
this.checkExpiration();
return this.http.put<Tretorno>(url, model, {
headers: {
'Authorization': 'Bearer ' + this.auth.getAuth()
}
}).pipe(
catchError(error => {
if (error?.status === 403 && error?.error?.error?.reason === 'PREMIUM_REQUIRED') {
return EMPTY;
}
})
);
}
Example #12
Source File: ignore-not-found.ts From ngx-operators with MIT License | 6 votes |
/**
* If the underlying request throws with a 404 error, it will swallow the error
* and complete the observable instead. All other errors will be rethrown.
*
* You can then set a fallback value with `defaultIfEmpty`.
*
* @returns stream which will map 404 errors to `undefined`
* @example
* this.http.get<User>('/users/123').pipe(
* ignoreNotFound()
* )
*/
export function ignoreNotFound<T>(): (source: Observable<T>) => Observable<T> {
return (source: Observable<T>): Observable<T> =>
source.pipe(
catchError(error => {
if (error instanceof HttpResponseBase && error.status === 404) {
return EMPTY;
}
return throwError(error);
})
);
}
Example #13
Source File: details.page.ts From capture-lite with GNU General Public License v3.0 | 6 votes |
private openIpfsSupportingVideo() {
return this.activeDetailedCapture$
.pipe(
first(),
switchMap(
activeDetailedCapture => activeDetailedCapture.diaBackendAsset$
),
isNonNullable(),
switchMap(diaBackendAsset => {
if (!diaBackendAsset.supporting_file) return EMPTY;
return Browser.open({
url: diaBackendAsset.supporting_file.replace(
'ipfs://',
'https://ipfs-pin.numbersprotocol.io/ipfs/'
),
toolbarColor: '#564dfc',
});
}),
untilDestroyed(this)
)
.subscribe();
}
Example #14
Source File: favourites.component.ts From open-genes-frontend with Mozilla Public License 2.0 | 6 votes |
private getData(): void {
this.favouritesService
.getItems()
.pipe(
switchMap((idList) => {
if (idList) {
this.favouriteGenesIds = idList;
this.cdRef.markForCheck();
return this.apiService.getGenesV2();
}
return EMPTY;
}),
takeUntil(this.subscription$)
)
.subscribe(
(filteredGenes) => {
this.genes = filteredGenes.items;
const queryParamsId = this.route.snapshot.queryParams.selected;
const queryParamsIdSplit = queryParamsId?.split(',');
if (queryParamsId) {
this.favouriteGenes = filteredGenes.items.filter((gene) => queryParamsIdSplit.includes(gene.id.toString()));
this.isSharedList = true;
} else {
this.favouriteGenes = filteredGenes.items.filter((gene) => this.favouriteGenesIds.includes(gene.id));
}
this.cdRef.markForCheck();
},
(err) => {
this.error = err;
}
);
}
Example #15
Source File: ledge-editor.component.ts From ledge with Mozilla Public License 2.0 | 6 votes |
constructor(public translate: TranslateService, private storage: StorageMap) {
this.searchSubscription = this.term$
.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap((term) => {
this.content = term;
this.storage.set(storyKey, term).subscribe();
return EMPTY;
})
)
.subscribe();
}
Example #16
Source File: rfm.web.service.ts From sba-angular with MIT License | 6 votes |
/**
* Get RFM data for a set of results
*
* @param rfm The name of the RFM
* @param results The results for which to retrieve RFM data
*/
getRfmData(rfm: string, results: Results): Observable<MapOf<RFMData>> {
const ids: string[] = [];
for (const record of results.records) {
if (!!record.flags && record.flags.indexOf("r") !== -1) {
ids.push(record.id);
}
}
if (ids.length === 0) {
return EMPTY;
}
const data = {
rfm,
queryHash: results.rfmQueryHash,
ids
};
const observable = this.httpClient.post<MapOf<RFMData>>(this.makeUrl(RfmWebService.endpoint), data);
Utils.subscribe(observable,
(response) => {
return response;
},
(error) => {
console.log("rfmService.getRfmData failure - error: ", error);
});
return observable;
}
Example #17
Source File: upcdatabase.service.ts From pantry_party with Apache License 2.0 | 6 votes |
lookForBarcode(barcode: string): Observable<ExternalProduct> {
if (!this.available) {
return EMPTY;
}
return this.http.post(
"https://www.upcdatabase.com/xmlrpc",
`<?xml version="1.0"?>
<methodCall>
<methodName>lookup</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>rpc_key</name>
<value><string>${this.apiKey}</string></value>
</member>
<member>
<name>upc</name>
<value><string>${convertToUpcAIfRequired(barcode)}</string></value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>`,
{ responseType: "text" }
) .pipe(
switchMap(r => this.decodeResponse(r)),
catchError(() => empty())
);
}
Example #18
Source File: add.ts From ble with Apache License 2.0 | 6 votes |
addVertexOrEntity: Epic = (action$, { store }) => {
return action$.pipe(
// we listen specifically on the background because when a user clicks another object they
// probably expect to select it
ofType('backgroundPointerDown'),
pluck('ev', 'data'),
filter((data) => data.button === 0 || data.pointerType === 'touch'),
map(({ global }) => store.editor.screenToWorld({
x: global.x,
y: global.y,
})),
map((posInWorld) => snapToGrid(posInWorld, store.editor.gridCellSize)),
filter(() => store.editor.mode === EditorMode.addVertex || store.editor.mode === EditorMode.addBlock),
mergeMap((posInWorld: IPoint) => {
switch (store.editor.mode) {
case EditorMode.addVertex:
return of({
type: 'addVertex',
pos: posInWorld,
});
case EditorMode.addBlock:
return of({
type: 'createEntity',
pos: posInWorld,
});
}
return empty();
}),
);
}
Example #19
Source File: my-trades.service.ts From rubic-app with GNU General Public License v3.0 | 5 votes |
public updateTableTrades(page = 0, pageSize = 10): Observable<TableTrade[]> {
return combineLatest([
this.authService.getCurrentUser().pipe(filter(user => user !== undefined)),
this.tokensService.tokens$.pipe(
filter(tokens => !!tokens),
first()
)
]).pipe(
switchMap(([user, tokens]) => {
this.tokens = tokens;
this.walletAddress = user?.address || null;
if (!this.walletAddress || !tokens.size) {
this._tableData$.next({
totalCount: 0,
trades: []
});
return EMPTY;
}
return forkJoin([
this.getBridgeTransactions(),
this.getCrossChainTrades(page, pageSize),
this.symbiosisService.getUserTrades()
]).pipe(
map(([bridgeTrades, tableData, symbiosisTrades]) => {
const adjustedData = bridgeTrades
.concat(symbiosisTrades)
.concat(tableData.trades.flat())
.map(trade => ({
...trade,
transactionHashScanUrl: this.scannerLinkPipe.transform(
trade.fromTransactionHash || trade.toTransactionHash,
trade.fromTransactionHash
? trade?.fromToken?.blockchain
: trade?.toToken?.blockchain,
ADDRESS_TYPE.TRANSACTION
)
}));
this._tableData$.next({
totalCount: tableData.totalCount + bridgeTrades.length + symbiosisTrades.length,
trades: adjustedData
});
return adjustedData;
})
);
}),
first()
);
}
Example #20
Source File: product-detail.component.ts From Angular-ActionStreams with MIT License | 5 votes |
product$ = this.productService.product$
.pipe(
catchError(err => {
this.errorMessageSubject.next(err);
return EMPTY;
}));
Example #21
Source File: product-detail.component.ts From Angular-HigherOrderMapping with MIT License | 5 votes |
product$ = this.productService.product$
.pipe(
catchError(error => {
this.errorMessage = error;
return EMPTY;
}));
Example #22
Source File: broker-gateway.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 5 votes |
public async postMessage(channel: MessagingChannel, message: Message): Promise<void> {
if (isPlatformStopped()) {
throw GatewayErrors.PLATFORM_STOPPED_ERROR;
}
// If not connected to the broker, wait until connected. If connected, continue execution immediately
// without spawning a microtask. Otherwise, messages cannot be published during platform shutdown.
const brokerInfo = this._brokerInfo || await lastValueFrom(this._brokerInfo$);
const messageId = UUID.randomUUID();
const envelope: MessageEnvelope = {
transport: MessagingTransport.ClientToBroker,
channel: channel,
message: message,
};
envelope.message.headers
.set(MessageHeaders.MessageId, messageId)
.set(MessageHeaders.Timestamp, Date.now())
.set(MessageHeaders.AppSymbolicName, this._appSymbolicName)
.set(MessageHeaders.ClientId, brokerInfo.clientId);
// Install Promise that resolves once the broker has acknowledged the message, or that rejects otherwise.
const postError$ = new Subject<never>();
const whenPosted = new Promise<void>((resolve, reject) => {
merge(this.message$, postError$)
.pipe(
filterByTopicChannel<MessageDeliveryStatus>(messageId),
take(1),
pluckMessage(),
timeout({first: this._messageDeliveryTimeout, with: () => throwError(() => GatewayErrors.MESSAGE_DISPATCH_ERROR(this._messageDeliveryTimeout, envelope))}),
mergeMap(statusMessage => statusMessage.body!.ok ? EMPTY : throwError(() => statusMessage.body!.details)),
takeUntil(this._platformStopping$),
)
.subscribe({
error: reject,
complete: resolve,
});
});
try {
brokerInfo.window.postMessage(envelope, brokerInfo.origin);
}
catch (error) {
postError$.error(error);
}
await whenPosted;
}
Example #23
Source File: emote-card.component.ts From App with MIT License | 5 votes |
getTooltip(): Observable<string | undefined> {
return this.emote?.getName().pipe(
map(name => (name?.length ?? 0) >= 14 ? name : '')
) ?? EMPTY;
}
Example #24
Source File: anchor.component.ts From alauda-ui with MIT License | 5 votes |
ngAfterViewInit() {
const { injectId, containerEl, scrollableEl } = this.parent;
const pageContentEl = containerEl.closest('.aui-page__content');
const paddingTop = pageContentEl
? +getComputedStyle(pageContentEl).paddingTop.slice(0, -2)
: 0;
fromEvent(scrollableEl, 'scroll')
.pipe(
debounceTime(100),
switchMap(() => {
const { scrollTop } =
scrollableEl === window
? document.documentElement
: (scrollableEl as HTMLElement);
const activedItem =
this.items.find(
({ target }) =>
target.offsetTop +
target.offsetHeight / 2 +
((scrollableEl === window &&
(target.offsetParent as HTMLElement)?.offsetTop) ||
0) >
scrollTop + paddingTop,
) || last(this.items);
return activedItem ? of(activedItem) : EMPTY;
}),
tap(activedItem => {
if (activedItem.id) {
this.activeId = activedItem.id;
this.cdr.markForCheck();
}
}),
debounceTime(100),
tap(activedItem => {
if (injectId && activedItem.id) {
history.replaceState(
null,
null,
location.pathname + location.search + '#' + activedItem.id,
);
}
}),
takeUntil(this.destroy$$),
)
.subscribe();
}
Example #25
Source File: add-relationship-button.component.ts From attack-workbench-frontend with Apache License 2.0 | 5 votes |
public createRelationship() {
let relationship = new Relationship();
relationship.relationship_type = this.config.relationship_type;
let initializer = null;
if (this.config.source_object) initializer = relationship.set_source_object(this.config.source_object, this.restApiService);
else if (this.config.source_ref) initializer = relationship.set_source_ref(this.config.source_ref, this.restApiService);
else if (this.config.target_object) initializer = relationship.set_target_object(this.config.target_object, this.restApiService);
else if (this.config.target_ref) initializer = relationship.set_target_ref(this.config.target_ref, this.restApiService);
else initializer = EMPTY;
this.loading = true;
var zip_subscription = initializer.subscribe({
next: () => {
this.loading = false;
let config: StixViewConfig = {
object: relationship,
editable: true,
mode: "edit",
sidebarControl: "events"
}
// if a dialog reference is provided, replace the active
// content with the relationship edit interface. This prevents
// a new dialog from opening over the current dialog.
if (this.config.dialog && this.config.dialog.componentInstance) {
this.config.dialog.componentInstance._config = config;
this.config.dialog.componentInstance.prevObject = this.config.source_object ? this.config.source_object : this.config.target_object;
this.config.dialog.componentInstance.startEditing();
return;
}
// open a new dialog
let prompt = this.dialog.open(StixDialogComponent, {
data: config,
maxHeight: "75vh"
})
let subscription = prompt.afterClosed().subscribe({
next: result => { if (prompt.componentInstance.dirty) this.created.emit(); }, //re-fetch values since an edit occurred
complete: () => { subscription.unsubscribe(); }
});
},
complete: () => { if (zip_subscription) zip_subscription.unsubscribe(); } //for some reason zip_subscription doesn't exist if using set_source_object or set_target_object
})
}
Example #26
Source File: account.service.ts From angular-10-facebook-login-example with MIT License | 5 votes |
facebookLogin() {
// login with facebook and return observable with fb access token on success
return from(new Promise<fb.StatusResponse>(resolve => FB.login(resolve)))
.pipe(concatMap(({ authResponse }) => {
if (!authResponse) return EMPTY;
return of(authResponse.accessToken);
}));
}
Example #27
Source File: rxjs-resource.spec.ts From slickgrid-universal with MIT License | 5 votes |
describe('RxJs Resource', () => {
let service: RxJsResource;
beforeEach(() => {
service = new RxJsResource();
});
it('should create the service', () => {
expect(service).toBeTruthy();
expect(service.className).toBe('RxJsResource');
});
it('should be able to create an RxJS Observable', () => {
const observable1 = service.createObservable();
const observable2 = service.of(1, 2, 3);
expect(observable1 instanceof Observable).toBeTruthy();
expect(observable2 instanceof Observable).toBeTruthy();
expect(service.isObservable(observable1)).toBeTruthy();
expect(service.isObservable(observable2)).toBeTruthy();
});
it('should be able to create an RxJS Subject', () => {
const subject = service.createSubject();
expect(subject instanceof Subject).toBeTruthy();
});
it('should be able to retrieve the RxJS EMPTY constant from the service getter', () => {
expect(service.EMPTY).toEqual(EMPTY);
});
it('should be able to execute the "iif" method and expect an Observable returned', () => {
const observable = service.createObservable();
const iifOutput = service.iif(() => isObservable(observable));
expect(iifOutput instanceof Observable).toBeTruthy();
});
it('should be able to execute the "firstValueFrom" method and expect an Observable returned', () => {
const observable = service.createObservable();
const output = service.firstValueFrom(observable);
expect(output instanceof Promise).toBeTruthy();
});
it('should be able to execute the "switchMap" method and expect an Observable returned', () => {
const observable = service.createObservable();
const output = observable.pipe(service.switchMap(() => service.createObservable()));
expect(output instanceof Observable).toBeTruthy();
});
it('should be able to execute the "takeUntil" method and expect an Observable returned', () => {
const observable = service.createObservable();
const iifOutput = service.iif(() => isObservable(observable));
const output = observable.pipe(service.takeUntil(iifOutput));
expect(output instanceof Observable).toBeTruthy();
});
});
Example #28
Source File: local.strategy.spec.ts From nestjs-rest-sample with GNU General Public License v3.0 | 5 votes |
describe('LocalStrategy', () => {
let strategy: LocalStrategy;
let authService: AuthService;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
providers: [
LocalStrategy,
{
provide: AuthService,
useValue: {
constructor: jest.fn(),
login: jest.fn(),
validateUser: jest.fn()
},
},
],
}).compile();
strategy = app.get<LocalStrategy>(LocalStrategy);
authService = app.get<AuthService>(AuthService);
});
describe('validate', () => {
it('should return user principal if user and password is provided ', async () => {
jest
.spyOn(authService, 'validateUser')
.mockImplementation((user: any, pass: any) => {
return of({
username: 'test',
id: '_id',
email: '[email protected]',
roles: [RoleType.USER],
});
});
const user = await strategy.validate('test', 'pass');
expect(user.username).toEqual('test');
expect(authService.validateUser).toBeCalledWith('test', 'pass');
});
it('should throw UnauthorizedException if user is not valid ', async () => {
jest
.spyOn(authService, 'validateUser')
.mockImplementation((user: any, pass: any) => {
return EMPTY;
});
try {
const user = await strategy.validate('test', 'pass');
} catch (e) {
//console.log(e)
expect(e).toBeDefined()
}
expect(authService.validateUser).toBeCalledWith('test', 'pass');
});
});
});
Example #29
Source File: details.page.ts From capture-lite with GNU General Public License v3.0 | 5 votes |
readonly detailedCaptures$: Observable<DetailedCapture[]> = this.type$.pipe(
switchMap(type => {
if (type === 'capture') return this.fromCaptures$;
if (type === 'post-capture') return this.fromPostCaptures$;
if (type === 'series') return this.fromSeries$;
return EMPTY;
})
);