Skip to content

feat(rx-dynamic-component): implement can load guards #37

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"@angular-eslint/template-parser": "12.3.1",
"@angular/compiler-cli": "12.2.6",
"@angular/language-service": "12.2.6",
"@hirez_io/observer-spy": "^2.1.0",
"@nestjs/testing": "^7.0.0",
"@nrwl/angular": "12.9.0",
"@nrwl/cli": "12.9.0",
Expand Down
7 changes: 7 additions & 0 deletions packages/rx-dynamic-component/router/redirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export class DynamicRedirect {
private readonly manifestId: string;

constructor(manifestId: string) {
this.manifestId = manifestId;
}
}
170 changes: 170 additions & 0 deletions packages/rx-dynamic-component/src/lib/can-import.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { Injectable, Injector } from '@angular/core';
import { subscribeSpyTo } from '@hirez_io/observer-spy';
import type { SpyObject } from '@ngneat/spectator/jest';
import { createSpyObject } from '@ngneat/spectator/jest';
import type { DynamicComponentManifest } from '@trellisorg/rx-dynamic-component';
import type { Observable } from 'rxjs';
import { of } from 'rxjs';
import type { CanImport } from './can-import';
import { isCanImport, runCanImports } from './can-import';

let result: Observable<boolean> | Promise<boolean> | boolean;

@Injectable()
export class MockCanImport implements CanImport {
canImport(
manifest: DynamicComponentManifest
): Observable<boolean> | Promise<boolean> | boolean {
return result;
}
}

@Injectable()
export class RandomClass {}

describe('CanImport', () => {
describe('isCanImport', () => {
it('should be a CanImport', () => {
expect(isCanImport(new MockCanImport())).toBe(true);
});

it('should not be a CanImport', () => {
expect(isCanImport(new RandomClass() as any)).toBe(false);
});
});

describe('runCanImports', () => {
let injector: SpyObject<Injector>;

const manifest: DynamicComponentManifest = {
loadChildren: () => Promise.resolve(),
componentId: '',
};

beforeEach(() => {
injector = createSpyObject(Injector, { get: jest.fn() });
});

it('should be true with no guards', () => {
expect(
subscribeSpyTo(
runCanImports(injector, manifest, [])
).getFirstValue()
).toEqual(true);
});

it('should be true with no valid guards', () => {
injector.get.mockReturnValue(new RandomClass());

expect(
subscribeSpyTo(
runCanImports(injector, manifest, [RandomClass as any])
).getFirstValue()
).toEqual(true);
});

it('should be true with one true observable', async () => {
const canImport = new MockCanImport();

jest.spyOn(canImport, 'canImport').mockReturnValue(of(true));

injector.get.mockReturnValue(canImport);

const subscriberSpy = subscribeSpyTo(
runCanImports(injector, manifest, [MockCanImport])
);

await subscriberSpy.onComplete();

expect(subscriberSpy.getLastValue()).toEqual(true);
});

it('should be true with one true observable and one true promise', async () => {
const canImport1 = new MockCanImport();

const canImport2 = new MockCanImport();

jest.spyOn(canImport1, 'canImport').mockReturnValue(of(true));
jest.spyOn(canImport2, 'canImport').mockReturnValue(
Promise.resolve(true)
);

injector.get
.mockReturnValueOnce(canImport1)
.mockReturnValueOnce(canImport2);

const subscriberSpy = subscribeSpyTo(
runCanImports(injector, manifest, [
MockCanImport,
MockCanImport,
])
);

await subscriberSpy.onComplete();

expect(subscriberSpy.getLastValue()).toEqual(true);
});

it('should be true with one true observable and one true promise and one true', async () => {
const canImport1 = new MockCanImport();

const canImport2 = new MockCanImport();

const canImport3 = new MockCanImport();

jest.spyOn(canImport1, 'canImport').mockReturnValue(of(true));
jest.spyOn(canImport2, 'canImport').mockReturnValue(
Promise.resolve(true)
);
jest.spyOn(canImport3, 'canImport').mockReturnValue(true);

injector.get
.mockReturnValueOnce(canImport1)
.mockReturnValueOnce(canImport2)
.mockReturnValueOnce(canImport3);

const subscriberSpy = subscribeSpyTo(
runCanImports(injector, manifest, [
MockCanImport,
MockCanImport,
MockCanImport,
])
);

await subscriberSpy.onComplete();

expect(subscriberSpy.getLastValue()).toEqual(true);
});

it('should be false if any are false', async () => {
const canImport1 = new MockCanImport();

const canImport2 = new MockCanImport();

const canImport3 = new MockCanImport();

jest.spyOn(canImport1, 'canImport').mockReturnValue(of(true));
jest.spyOn(canImport2, 'canImport').mockReturnValue(
Promise.resolve(true)
);
jest.spyOn(canImport3, 'canImport').mockReturnValue(false);

injector.get
.mockReturnValueOnce(canImport1)
.mockReturnValueOnce(canImport2)
.mockReturnValueOnce(canImport3);

const subscriberSpy = subscribeSpyTo(
runCanImports(injector, manifest, [
MockCanImport,
MockCanImport,
MockCanImport,
])
);

await subscriberSpy.onComplete();

expect(subscriberSpy.getLastValue()).toEqual(false);
});
});
});
50 changes: 50 additions & 0 deletions packages/rx-dynamic-component/src/lib/can-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { Injector } from '@angular/core';
import type { Observable } from 'rxjs';
import { forkJoin, of } from 'rxjs';
import { first, map } from 'rxjs/operators';
import type { DynamicComponentManifest } from './manifest';
import { isFunction, wrapIntoObservable } from './utils';

/**
* A Guard that is run before loading the manifest
*/
export interface CanImport {
canImport(
manifest: DynamicComponentManifest
): Observable<boolean> | Promise<boolean> | boolean;
}

export function isCanImport<T extends CanImport>(canImport: T): canImport is T {
return canImport && isFunction<CanImport>(canImport.canImport);
}

export function inject(injector: Injector, token: any): any {
return injector.get(token);
}

export function runCanImports(
injector: Injector,
manifest: DynamicComponentManifest,
canImports: any[]
): Observable<boolean> {
if (!Array.isArray(canImports) || canImports.length === 0) {
return of(true);
}

const tokens = canImports.map((token) => inject(injector, token));

const validTokens = tokens.filter(isCanImport);

const obs = validTokens.map((canImport) =>
wrapIntoObservable(canImport.canImport(manifest)).pipe(first())
);

if (obs.length === 0) {
return of(true);
}

return forkJoin(obs).pipe(
// Using some instead of every is more efficient as we only need one failure to fail the whole thing
map((results) => !results.some((result) => result === false))
);
}
2 changes: 2 additions & 0 deletions packages/rx-dynamic-component/src/lib/manifest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { InjectionToken } from '@angular/core';
import type { LoadChildrenCallback } from '@angular/router';
import type { CanImport } from './can-import';

export type ManifestMap = Map<string, DynamicComponentManifest>;

Expand Down Expand Up @@ -58,6 +59,7 @@ export interface DynamicComponentManifest<T = string>
extends SharedManifestConfig {
componentId: T;
loadChildren: LoadChildrenCallback;
canImport?: CanImport[];
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { isPlatformBrowser } from '@angular/common';
import { Inject, Injectable, NgZone, PLATFORM_ID } from '@angular/core';
import {
Inject,
Injectable,
Injector,
NgZone,
PLATFORM_ID,
} from '@angular/core';
import type { Observable } from 'rxjs';
import { isObservable } from 'rxjs';
import { isObservable, of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { runCanImports } from './can-import';
import { Logger } from './logger';
import {
DEFAULT_TIMEOUT,
Expand All @@ -10,6 +18,7 @@ import {
DynamicManifestPreloadPriority,
DYNAMIC_COMPONENT_CONFIG,
} from './manifest';
import { wrapIntoObservable } from './utils';

/*
* TODO: Remove IdleDeadline and requestIdleCallback typing once upgrade to 4.4
Expand Down Expand Up @@ -50,7 +59,8 @@ export class RxDynamicComponentPreloaderService {
private _ngZone: NgZone,
private logger: Logger,
// eslint-disable-next-line @typescript-eslint/ban-types
@Inject(PLATFORM_ID) platformId: Object
@Inject(PLATFORM_ID) platformId: Object,
private _injector: Injector
) {
this.isBrowser = isPlatformBrowser(platformId);
}
Expand Down Expand Up @@ -152,15 +162,30 @@ export class RxDynamicComponentPreloaderService {
}
}

async loadManifest(manifest: DynamicComponentManifest): Promise<void> {
async loadManifest(manifest: DynamicComponentManifest): Promise<boolean> {
this.logger.log(`Loading ${manifest.componentId}`);

const promiseOrObservable = manifest.loadChildren();

await (isObservable(promiseOrObservable)
? promiseOrObservable.toPromise()
: promiseOrObservable);
const canImportGuards = manifest.canImport ?? [];

return;
return runCanImports(this._injector, manifest, canImportGuards)
.pipe(
switchMap((canImport) =>
canImport
? wrapIntoObservable(promiseOrObservable).pipe(
map(() => true),
catchError((error) => {
this.logger.error(
`Failed to load ${manifest.componentId}`,
error
);
return of(false);
})
)
: of(false)
)
)
.toPromise();
}
}
26 changes: 26 additions & 0 deletions packages/rx-dynamic-component/src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {
ɵisObservable as isObservable,
ɵisPromise as isPromise,
} from '@angular/core';
import { from, Observable, of } from 'rxjs';

export function isFunction<T>(v: any): v is T {
return typeof v === 'function';
}

export function wrapIntoObservable<T>(
value: T | Promise<T> | Observable<T>
): Observable<T> {
if (isObservable(value)) {
return value;
}

if (isPromise(value)) {
// Use `Promise.resolve()` to wrap promise-like instances.
// Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the
// change detection.
return from(Promise.resolve(value));
}

return of(value);
}
3 changes: 3 additions & 0 deletions packages/rx-dynamic-component/test-setup.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
import { autoUnsubscribe } from '@hirez_io/observer-spy';
import 'jest-preset-angular/setup-jest';

autoUnsubscribe();
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1707,6 +1707,11 @@
lodash.camelcase "^4.3.0"
protobufjs "^6.8.6"

"@hirez_io/observer-spy@^2.1.0":
version "2.1.0"
resolved "https://registry.yarnpkg.com/@hirez_io/observer-spy/-/observer-spy-2.1.0.tgz#2c531366385763437d18af8b751e0eb0f2ad82f6"
integrity sha512-wGLRpUq3Qhcyyx2oQmx2HWe2trp6tpkUvz3U9Uqq5eywXL9uV0W9+QkeBzif8axhOQlq7Xngs9pC0S611+hkLg==

"@istanbuljs/load-nyc-config@^1.0.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced"
Expand Down