Skip to content
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

All notable changes to this project will be documented in this file.

## 2026-11-21 - version 1.4.5

- **GET requests retry transient failures.** One network blip used to put the Projects app straight into "Failed to load projects". A functional interceptor, `retryTransientErrors`, now retries any GET that fails with a network error (status 0) or a 5xx, twice, 400ms and then 800ms later. A 404 fails straight away, and nothing but GETs is ever retried, because a retried POST is a second submission
- **Angular guide, lesson 06: RxJS and HTTP** (`/thoughts/angular-06-rxjs`). The live demo runs two search boxes over a deliberately slow fake server, where one-letter queries answer slowest. Type "sig" and mergeMap ends on the stale "s" results while switchMap shows "sig". The operator behind it has marble tests on `TestScheduler`
- Initial bundle 384.98 kB → 389.82 kB. I measured the parts: without the interceptor it's 389.00 kB, and without lesson 06 registered it's 388.39 kB. RxJS's timer and async-scheduler code is shared by the interceptor's backoff and the lesson's `delay`, so it lands in an eager chunk either way. I tried writing the demo with `timer` instead of `delay`, and it saved 0.26 kB, not enough to beat the more readable version. That leaves 10 kB of headroom, so the remaining lessons have to stay out of eager code

## 2026-11-21 - version 1.4.4

- **Saved reading progress for the Angular guide**: every lesson ends with a "Mark lesson complete" toggle (a real `aria-pressed` button whose label changes too, so the state isn't colour alone). The series nav counts "N of M complete", and the Thoughts list badges completed lessons. Progress is kept in localStorage
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "angular-paul",
"version": "1.4.4",
"version": "1.4.5",
"scripts": {
"ng": "ng",
"start": "ng serve",
Expand Down
8 changes: 6 additions & 2 deletions src/app/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ import {
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection,
} from '@angular/core';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { retryTransientErrors } from './shared/retry-transient-errors.interceptor';
import {
provideClientHydration,
withEventReplay,
Expand All @@ -32,7 +33,10 @@ export const appConfig: ApplicationConfig = {
// Covered properly in lesson 09.
provideZonelessChangeDetection(),
// HttpClient backed by fetch() instead of XHR — required for good SSR.
provideHttpClient(withFetch()),
// [ng-06 rxjs] Interceptors run in array order on the way out and reverse
// order on the way back. withInterceptors() takes plain functions; the
// class-based HTTP_INTERCEPTORS multi-provider is the legacy form.
provideHttpClient(withFetch(), withInterceptors([retryTransientErrors])),
provideRouter(routes),
// SSR hydration: reuse server-rendered DOM instead of re-creating it.
// Lesson 12.
Expand Down
107 changes: 107 additions & 0 deletions src/app/shared/retry-transient-errors.interceptor.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { appConfig } from '../app.config';
import { retryTransientErrors } from './retry-transient-errors.interceptor';

const UNAVAILABLE = { status: 503, statusText: 'Service Unavailable' };

describe('retryTransientErrors', () => {
let http: HttpClient;
let backend: HttpTestingController;
let result: unknown;
let failure: { status?: number } | undefined;

const get = (url = '/repos') =>
http.get(url).subscribe({ next: (body) => (result = body), error: (error) => (failure = error) });

beforeEach(() => {
vi.useFakeTimers();
result = undefined;
failure = undefined;
TestBed.configureTestingModule({
providers: [provideHttpClient(withInterceptors([retryTransientErrors])), provideHttpClientTesting()],
});
http = TestBed.inject(HttpClient);
backend = TestBed.inject(HttpTestingController);
});

afterEach(() => {
backend.verify();
vi.useRealTimers();
});

it('retries a GET that hit a 5xx, after a backoff delay', () => {
get();
backend.expectOne('/repos').flush('down', UNAVAILABLE);

backend.expectNone('/repos');
vi.advanceTimersByTime(500);
backend.expectOne('/repos').flush(['angular-paul']);

expect(result).toEqual(['angular-paul']);
expect(failure).toBeUndefined();
});

it('treats a network failure (status 0) as transient too', () => {
get();
backend.expectOne('/repos').error(new ProgressEvent('error'));
vi.advanceTimersByTime(500);
backend.expectOne('/repos').flush([]);

expect(result).toEqual([]);
});

it('backs off longer each time, then gives up after two retries with the last error', () => {
get();
backend.expectOne('/repos').flush('down', UNAVAILABLE);
vi.advanceTimersByTime(500);
backend.expectOne('/repos').flush('down', UNAVAILABLE);

vi.advanceTimersByTime(500);
backend.expectNone('/repos');
vi.advanceTimersByTime(500);
backend.expectOne('/repos').flush('still down', UNAVAILABLE);

vi.advanceTimersByTime(10_000);
backend.expectNone('/repos');
expect(failure?.status).toBe(503);
});

it('does not retry a client error like 404', () => {
get();
backend.expectOne('/repos').flush('nope', { status: 404, statusText: 'Not Found' });

vi.advanceTimersByTime(10_000);
backend.expectNone('/repos');
expect(failure?.status).toBe(404);
});

it('never retries a POST, which might not be safe to send twice', () => {
http.post('/messages', { text: 'hi' }).subscribe({ error: (error) => (failure = error) });
backend.expectOne('/messages').flush('down', UNAVAILABLE);

vi.advanceTimersByTime(10_000);
backend.expectNone('/messages');
expect(failure?.status).toBe(503);
});
});

describe('retryTransientErrors in the app config', () => {
it('is registered on the app HttpClient', () => {
TestBed.configureTestingModule({ providers: [...appConfig.providers, provideHttpClientTesting()] });
vi.useFakeTimers();
const backend = TestBed.inject(HttpTestingController);
let result: unknown;

TestBed.inject(HttpClient)
.get('https://api.github.com/users/gpbsumido/repos')
.subscribe((body) => (result = body));
backend.expectOne(() => true).flush('down', UNAVAILABLE);
vi.advanceTimersByTime(500);
backend.expectOne(() => true).flush([]);

expect(result).toEqual([]);
vi.useRealTimers();
});
});
36 changes: 36 additions & 0 deletions src/app/shared/retry-transient-errors.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { retry, throwError, timer } from 'rxjs';

const MAX_RETRIES = 2;
const BASE_DELAY_MS = 400;

// [ng-06 rxjs] A functional interceptor: a plain function that sees every
// request HttpClient makes. `next(req)` sends it on and returns the response
// as an Observable, so the interceptor can pipe operators onto it.
//
// Simple: one blip on the network used to show the Projects app's error
// state. Now GETs get two more tries before anyone sees an error.
// Intermediate: retry() resubscribes to the source on error. HttpClient
// Observables are cold, so resubscribing *sends the request again*. That's
// what makes this work, and why it must stay away from POSTs.
// Expert: retry's `delay` returns an Observable. When it emits, retry tries
// again; when it errors, the error goes downstream. So "don't retry a 404"
// is just throwError() from the delay function, and the backoff is a
// timer() that doubles: 400ms, then 800ms.
export const retryTransientErrors: HttpInterceptorFn = (req, next) => {
// Only GETs are safe to send twice. A retried POST could submit twice.
if (req.method !== 'GET') return next(req);

return next(req).pipe(
retry({
count: MAX_RETRIES,
delay: (error, retryCount) =>
isTransient(error) ? timer(BASE_DELAY_MS * 2 ** (retryCount - 1)) : throwError(() => error),
}),
);
};

/** Status 0 is a network failure (offline, DNS, CORS); 5xx is the server's problem. */
function isTransient(error: unknown): boolean {
return error instanceof HttpErrorResponse && (error.status === 0 || error.status >= 500);
}
57 changes: 57 additions & 0 deletions src/app/thoughts-content/lessons/lesson-06-rxjs.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import * as axeMatchers from 'vitest-axe/matchers';
import { axe } from '../../../test/a11y';
import { LESSON_PAGES } from './lessons';
import { Lesson06Rxjs } from './lesson-06-rxjs';

expect.extend(axeMatchers);

describe('Lesson06Rxjs', () => {
let fixture: ComponentFixture<Lesson06Rxjs>;
let el: HTMLElement;

const text = (selector: string) => el.querySelector(selector)?.textContent ?? '';
// Under fake timers the zoneless scheduler's own timeouts are fake too, so
// advancing the clock is what runs change detection, not whenStable().
const type = async (value: string) => {
const input = el.querySelector<HTMLInputElement>('#race-query')!;
input.value = value;
input.dispatchEvent(new Event('input'));
await vi.advanceTimersByTimeAsync(20);
};

beforeEach(async () => {
await TestBed.configureTestingModule({ imports: [Lesson06Rxjs] }).compileComponents();
fixture = TestBed.createComponent(Lesson06Rxjs);
await fixture.whenStable();
el = fixture.nativeElement as HTMLElement;
});

afterEach(() => vi.useRealTimers());

it('is registered as the lesson page for its thought', () => {
expect(LESSON_PAGES['angular-06-rxjs']).toBeDefined();
});

it('teaches at three levels, then pitfalls and interview questions', () => {
const headings = [...el.querySelectorAll('h2')].map((h) => h.textContent?.trim());
expect(headings).toEqual(
expect.arrayContaining(['Simple', 'Intermediate', 'Expert', 'Pitfalls', 'Interview questions']),
);
});

it('typing fast leaves mergeMap showing a stale query and switchMap the current one', async () => {
vi.useFakeTimers();
await type('s');
await type('si');
await type('sig');
await vi.advanceTimersByTimeAsync(2000);

expect(text('#race-merge')).toContain('"s"');
expect(text('#race-switch')).toContain('"sig"');
});

it('has no axe violations', async () => {
expect(await axe(el)).toHaveNoViolations();
});
});
Loading
Loading