Skip to content

perf: reduce routing module bundle size #172

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

Merged
merged 1 commit into from
Jan 15, 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
@@ -0,0 +1,38 @@
import { MockProvider, MockService } from 'ng-mocks'
import { ActivatedRouteSnapshot } from '@angular/router'
import { TestBed } from '@angular/core/testing'
import {
CurrentRouteDataMetadataStrategy,
ROUTING_KEY,
} from './current-route-data-metadata-strategy'
import { MetadataService } from '../../core'

describe('Current route data metadata strategy', () => {
describe('resolve', () => {
it('returns current route snapshot (last child)', () => {
const dummyRouteMetadata = { title: 'dummy' }
const rootSnapshot = MockService(ActivatedRouteSnapshot, {
firstChild: {
firstChild: {
firstChild: MockService(ActivatedRouteSnapshot, {
data: { [ROUTING_KEY]: dummyRouteMetadata },
}),
},
},
} as Partial<ActivatedRouteSnapshot>)
const sut = makeSut()

expect(sut.resolve(rootSnapshot)).toEqual(dummyRouteMetadata)
})
})
})

function makeSut() {
TestBed.configureTestingModule({
providers: [
CurrentRouteDataMetadataStrategy,
MockProvider(MetadataService),
],
})
return TestBed.inject(CurrentRouteDataMetadataStrategy)
}
Original file line number Diff line number Diff line change
@@ -1,33 +1,26 @@
import { ActivatedRouteSnapshot } from '@angular/router'
import { Inject, Injectable } from '@angular/core'
import {
GET_CURRENT_SNAPSHOT_FROM_ROOT_SNAPSHOT_TOKEN,
GetCurrentSnapshotFromRootSnapshot,
} from './get-current-snapshot-from-root-snapshot'
import { Injectable } from '@angular/core'
import { MetadataRouteStrategy } from './metadata-route-strategy'
import { MetadataService, MetadataValues } from '@davidlj95/ngx-meta/core'
import { MetadataRouteData } from './metadata-route-data'

@Injectable({ providedIn: 'root' })
export class CurrentRouteDataMetadataStrategy
implements MetadataRouteStrategy<MetadataValues>
{
constructor(
@Inject(GET_CURRENT_SNAPSHOT_FROM_ROOT_SNAPSHOT_TOKEN)
private readonly getCurrentSnapshotFromRootSnapshot: GetCurrentSnapshotFromRootSnapshot,
private readonly metadataService: MetadataService,
) {}
export class CurrentRouteDataMetadataStrategy implements MetadataRouteStrategy {
constructor(private readonly metadataService: MetadataService) {}

resolve<T extends object>(
routeSnapshot: ActivatedRouteSnapshot,
): T | undefined {
const currentRoute = this.getCurrentSnapshotFromRootSnapshot(routeSnapshot)
return currentRoute.data[ROUTING_KEY]
let currentRouteSnapshot: ActivatedRouteSnapshot = routeSnapshot
while (currentRouteSnapshot.firstChild != null) {
currentRouteSnapshot = currentRouteSnapshot.firstChild
}
return currentRouteSnapshot.data[ROUTING_KEY]
}

set(metadata: MetadataValues | undefined): void {
this.metadataService.set(metadata)
}
}

const ROUTING_KEY: keyof MetadataRouteData = 'meta'
export const ROUTING_KEY: keyof MetadataRouteData = 'meta'

This file was deleted.

This file was deleted.

2 changes: 1 addition & 1 deletion projects/ngx-meta/src/routing/src/metadata-route-data.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GlobalMetadata, MetadataValues } from '@davidlj95/ngx-meta/core'

export interface MetadataRouteData {
meta: GlobalMetadata | MetadataValues
meta: GlobalMetadata & MetadataValues
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,6 @@ describe('RouterListenerService', () => {

expect(events$.observed).toBeFalse()
})

it('should report is not listening', () => {
const sut = makeSut()

expect(sut.isListening).toBeFalse()
})
})

describe('when already listening', () => {
Expand All @@ -47,22 +41,18 @@ describe('RouterListenerService', () => {
sut.listen()
})

it('should report is listening', () => {
expect(sut.isListening).toBeTrue()
})

describe('when listening again', () => {
let existingSubscription: Subscription

beforeEach(() => {
existingSubscription = sut['subscription']!
existingSubscription = sut['sub']!
expect(existingSubscription).toBeDefined()
spyOn(console, 'warn').and.stub()
sut.listen()
})

it('should not subscribe again', () => {
expect(sut['subscription']).toBe(existingSubscription)
expect(sut['sub']).toBe(existingSubscription)
})

it('should warn about it', () => {
Expand Down Expand Up @@ -92,22 +82,19 @@ describe('RouterListenerService', () => {
it('should log it to console', () => {
const consoleWarn = spyOn(console, 'warn')
const events$ = new EventEmitter()
const sut = makeSut({
events$,
strategies: [],
})
const sut = makeSut({ events$ })

sut.listen()

events$.emit(makeNavigationEvent(EventType.NavigationEnd))

expect(consoleWarn).toHaveBeenCalledOnceWith(
jasmine.stringContaining('strategies'),
jasmine.stringContaining('strategy'),
)
})
})

describe('when a single strategy is found', () => {
describe('when a strategy is provided', () => {
it('should call strategy resolve and set', () => {
const metadata = { key: 'value' }
const strategy = makeStrategy('single', metadata)
Expand All @@ -129,40 +116,12 @@ describe('RouterListenerService', () => {
expect(strategy.set).toHaveBeenCalledOnceWith(metadata)
})
})

it('should call all strategies resolve and set in order', () => {
const events$ = new EventEmitter()
const strategyOneData = { key: 'one' }
const strategyOne = makeStrategy('one', strategyOneData)
const strategyTwoData = { key: 'two' }
const strategyTwo = makeStrategy('two', strategyTwoData)
const activatedRoute = MockService(ActivatedRoute)
const sut = makeSut({
events$,
strategies: [strategyOne, strategyTwo],
activatedRoute,
})
sut.listen()

events$.emit(makeNavigationEvent(EventType.NavigationEnd))

expect(strategyOne.resolve).toHaveBeenCalledOnceWith(
activatedRoute.snapshot,
)
expect(strategyOne.set).toHaveBeenCalledOnceWith(strategyOneData)
expect(strategyTwo.resolve).toHaveBeenCalledOnceWith(
activatedRoute.snapshot,
)
expect(strategyTwo.set).toHaveBeenCalledOnceWith(strategyTwoData)
expect(strategyOne.set).toHaveBeenCalledBefore(strategyTwo.set)
})
})
})

function makeSut(
opts: {
events$?: EventEmitter<NavigationEvent>
strategies?: ReadonlyArray<MetadataRouteStrategy>
strategy?: MetadataRouteStrategy
activatedRoute?: ActivatedRoute
} = {},
Expand All @@ -180,31 +139,11 @@ function makeSut(
MockProvider(ActivatedRoute, activatedRoute, 'useValue'),
]

if (opts.strategies) {
// multiple providers (or none if empty array)
for (const strategy of opts.strategies) {
providers.push(
MockProvider(MetadataRouteStrategy, strategy, 'useValue', true),
)
}
}
if (opts.strategy) {
// one provider only
providers.push(
MockProvider(MetadataRouteStrategy, opts.strategy, 'useValue'),
)
}
if (opts.strategies === undefined && opts.strategy === undefined) {
// default: one of many providers
providers.push(
MockProvider(
MetadataRouteStrategy,
MockService(MetadataRouteStrategy),
'useValue',
true,
),
)
}

TestBed.configureTestingModule({
providers,
Expand Down
27 changes: 8 additions & 19 deletions projects/ngx-meta/src/routing/src/router-listener.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ import { MetadataRouteStrategy } from './metadata-route-strategy'
export class RouterListenerService implements OnDestroy {
// Replace by `takeUntilDestroyed` when stable
// https://angular.io/api/core/rxjs-interop/takeUntilDestroyed
private subscription?: Subscription
private sub?: Subscription

constructor(
private readonly router: Router,
private readonly activatedRoute: ActivatedRoute,
@Optional()
@Inject(MetadataRouteStrategy)
private readonly metadataRouteStrategies: ReadonlyArray<MetadataRouteStrategy>,
private readonly strategy: MetadataRouteStrategy | null,
) {}

public listen() {
if (this.isListening) {
if (this.sub) {
if (ngDevMode) {
console.warn(
'NgxMetaRoutingModule was set to listen for route changes ' +
Expand All @@ -28,38 +28,27 @@ export class RouterListenerService implements OnDestroy {
return
}

this.subscription = this.router.events
this.sub = this.router.events
.pipe(filter(({ type }) => type === EventType.NavigationEnd))
.subscribe({
next: () => {
if (!this.metadataRouteStrategies) {
if (!this.strategy) {
if (ngDevMode) {
console.warn(
'`NgxMetaRoutingModule` tried to set metadata for this ' +
'route but no metadata route strategies were found. ' +
'route but no metadata route strategy was found. ' +
'Provide at least one `MetadataRouteStrategy` to be able ' +
'to resolve metadata from a route and set it in order to ' +
'fix this.',
)
}
return
}
const strategies = Array.isArray(this.metadataRouteStrategies)
? this.metadataRouteStrategies
: [this.metadataRouteStrategies]
for (const strategy of strategies) {
const data = strategy.resolve(this.activatedRoute.snapshot)
strategy.set(data)
}
this.strategy.set(this.strategy.resolve(this.activatedRoute.snapshot))
},
})
}

public get isListening(): boolean {
return !!this.subscription
}

ngOnDestroy(): void {
this.subscription?.unsubscribe()
this.sub?.unsubscribe()
}
}