From 631f72d496105368e7a59807c8f24b22bdfe0bbf Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:26:19 +0000 Subject: [PATCH 1/2] fix: wire app to local Spring Boot 3 backend (env apiUrl, articles POST path, non-errors error bodies, seed script, zone.js dev dep) --- README.md | 10 +++ angular.json | 15 ++++ e2e/error-handling.spec.ts | 2 +- e2e/health.spec.ts | 2 +- e2e/helpers/api.ts | 2 +- e2e/settings.spec.ts | 2 +- e2e/user-fetch-errors.spec.ts | 2 +- package.json | 2 + scripts/seed-local.ts | 84 +++++++++++++++++++ src/app/core/interceptors/api.interceptor.ts | 3 +- .../core/interceptors/error.interceptor.ts | 25 ++++-- src/app/core/models/errors.model.ts | 2 +- .../article/services/articles.service.spec.ts | 4 +- .../article/services/articles.service.ts | 2 +- .../components/list-errors.component.ts | 4 +- src/environments/environment.local.ts | 4 + src/environments/environment.ts | 4 + 17 files changed, 150 insertions(+), 19 deletions(-) create mode 100644 scripts/seed-local.ts create mode 100644 src/environments/environment.local.ts create mode 100644 src/environments/environment.ts diff --git a/README.md b/README.md index dc3c5daaf..514d17d56 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,16 @@ bun run start Run `bun run setup` again after a `git pull` that updates the `realworld` submodule. +### Running against a local backend + +The API base URL comes from `src/environments/environment.ts` (default `https://api.realworld.show/api`). The `local` configuration swaps in `src/environments/environment.local.ts`, which points at `http://localhost:8080` (for example the [Spring Boot backend](https://github.com/COG-GTM/spring-boot-realworld-example-app) started with `./gradlew bootRun`). + +```bash +bun run seed:local # optional: users jake/ana/sam (password123), 27 tagged articles, comments, favorites, follows +bun run start:local # dev server at localhost:4200 using http://localhost:8080 +API_URL=http://localhost:8080 bun run test:e2e # e2e suite against the same backend +``` + ### Building the project Run `bun run build` to build the project. The build artifacts will be stored in the `dist/` directory. diff --git a/angular.json b/angular.json index e90b20c95..9da6f0122 100644 --- a/angular.json +++ b/angular.json @@ -57,6 +57,18 @@ "extractLicenses": false, "sourceMap": true, "namedChunks": true + }, + "local": { + "optimization": false, + "extractLicenses": false, + "sourceMap": true, + "namedChunks": true, + "fileReplacements": [ + { + "replace": "src/environments/environment.ts", + "with": "src/environments/environment.local.ts" + } + ] } }, "defaultConfiguration": "production" @@ -69,6 +81,9 @@ }, "development": { "buildTarget": "angular-conduit:build:development" + }, + "local": { + "buildTarget": "angular-conduit:build:local" } }, "defaultConfiguration": "development" diff --git a/e2e/error-handling.spec.ts b/e2e/error-handling.spec.ts index 02e46f8bc..380c8f4a1 100644 --- a/e2e/error-handling.spec.ts +++ b/e2e/error-handling.spec.ts @@ -1,6 +1,6 @@ import { test, expect, Page, Route } from '@playwright/test'; -const API_BASE = 'https://api.realworld.show/api'; +const API_BASE = process.env['API_URL'] ?? 'https://api.realworld.show/api'; /** * Helper to mock an API endpoint with a specific error response diff --git a/e2e/health.spec.ts b/e2e/health.spec.ts index 004b32610..a7337c8a4 100644 --- a/e2e/health.spec.ts +++ b/e2e/health.spec.ts @@ -12,7 +12,7 @@ test.describe('Health Checks', () => { }); test('API should be accessible', async ({ page }) => { - const tagsUrl = 'https://api.realworld.show/api/tags'; + const tagsUrl = `${process.env['API_URL'] ?? 'https://api.realworld.show/api'}/tags`; const mockTags = { tags: ['angular', 'react', 'vue'] }; let routeHits = 0; diff --git a/e2e/helpers/api.ts b/e2e/helpers/api.ts index 4fbe1eb1c..25acdc20b 100644 --- a/e2e/helpers/api.ts +++ b/e2e/helpers/api.ts @@ -1,6 +1,6 @@ import { APIRequestContext } from '@playwright/test'; -const API_BASE = 'https://api.realworld.show/api'; +const API_BASE = process.env['API_URL'] ?? 'https://api.realworld.show/api'; export interface UserCredentials { email: string; diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts index 10a7c8440..23b7fe459 100644 --- a/e2e/settings.spec.ts +++ b/e2e/settings.spec.ts @@ -2,7 +2,7 @@ import { test, expect } from '@playwright/test'; import { register, generateUniqueUser } from './helpers/auth'; import { getToken, getCurrentUser } from './helpers/debug'; -const API_BASE = 'https://api.realworld.show/api'; +const API_BASE = process.env['API_URL'] ?? 'https://api.realworld.show/api'; /** * Tests for the settings/profile update feature. diff --git a/e2e/user-fetch-errors.spec.ts b/e2e/user-fetch-errors.spec.ts index 2540b71e6..0dfdd2592 100644 --- a/e2e/user-fetch-errors.spec.ts +++ b/e2e/user-fetch-errors.spec.ts @@ -1,7 +1,7 @@ import { test, expect } from '@playwright/test'; import { getToken, getAuthState } from './helpers/debug'; -const API_BASE = 'https://api.realworld.show/api'; +const API_BASE = process.env['API_URL'] ?? 'https://api.realworld.show/api'; /** * Tests for error handling when the app tries to fetch the current user on initialization. diff --git a/package.json b/package.json index 0cbe061c1..987b6c4d5 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,8 @@ "ng": "ng", "setup": "git submodule init && git submodule update && bun install", "start": "ng serve", + "start:local": "ng serve --configuration local", + "seed:local": "bun scripts/seed-local.ts", "build": "ng build", "test": "vitest", "test:ui": "vitest --ui", diff --git a/scripts/seed-local.ts b/scripts/seed-local.ts new file mode 100644 index 000000000..3c49e41f1 --- /dev/null +++ b/scripts/seed-local.ts @@ -0,0 +1,84 @@ +/** + * Seeds a local RealWorld backend (default http://localhost:8080) with users, + * follows, tagged articles (enough for pagination), comments and favorites. + * + * Usage: API_URL=http://localhost:8080 bun scripts/seed-local.ts + */ +const API_URL = process.env['API_URL'] ?? 'http://localhost:8080'; +const PASSWORD = 'password123'; +const USERS = ['jake', 'ana', 'sam']; +const TAGS = ['angular', 'spring', 'java', 'rxjs', 'testing']; +const ARTICLES_PER_USER = 9; + +async function call(method: string, path: string, body?: unknown, token?: string): Promise { + const res = await fetch(`${API_URL}${path}`, { + method, + headers: { + 'Content-Type': 'application/json', + ...(token ? { Authorization: `Token ${token}` } : {}), + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!res.ok) { + throw new Error(`${method} ${path} -> ${res.status} ${await res.text()}`); + } + return (res.status === 204 ? undefined : await res.json()) as T; +} + +async function signIn(username: string): Promise { + const user = { username, email: `${username}@example.com`, password: PASSWORD }; + try { + return (await call<{ user: { token: string } }>('POST', '/users', { user })).user.token; + } catch { + const { email, password } = user; + return (await call<{ user: { token: string } }>('POST', '/users/login', { user: { email, password } })).user.token; + } +} + +async function main(): Promise { + const tokens: Record = {}; + for (const username of USERS) { + tokens[username] = await signIn(username); + } + + const [jake, ana, sam] = USERS; + await call('POST', `/profiles/${ana}/follow`, {}, tokens[jake]); + await call('POST', `/profiles/${sam}/follow`, {}, tokens[jake]); + await call('POST', `/profiles/${jake}/follow`, {}, tokens[ana]); + + const slugs: string[] = []; + for (const [u, username] of USERS.entries()) { + for (let i = 1; i <= ARTICLES_PER_USER; i++) { + const article = { + title: `${username} seed article ${i} ${Date.now()}`, + description: `Seed article ${i} by ${username}`, + body: `# Seed article ${i}\n\nWritten by **${username}** for local runs.`, + tagList: [TAGS[(u + i) % TAGS.length], TAGS[(u + i + 1) % TAGS.length]], + }; + const { article: created } = await call<{ article: { slug: string } }>( + 'POST', + '/articles', + { article }, + tokens[username], + ); + slugs.push(created.slug); + } + } + + for (const [i, slug] of slugs.entries()) { + const commenter = USERS[(i + 1) % USERS.length]; + await call('POST', `/articles/${slug}/comments`, { comment: { body: `Nice post (${i + 1})` } }, tokens[commenter]); + if (i % 3 === 0) { + await call('POST', `/articles/${slug}/favorite`, {}, tokens[commenter]); + } + } + + console.log( + `Seeded ${API_URL}: users ${USERS.join(', ')} (password "${PASSWORD}"), ${slugs.length} articles, tags ${TAGS.join(', ')}`, + ); +} + +main().catch(err => { + console.error(err); + process.exit(1); +}); diff --git a/src/app/core/interceptors/api.interceptor.ts b/src/app/core/interceptors/api.interceptor.ts index 32160a1ee..563222d1f 100644 --- a/src/app/core/interceptors/api.interceptor.ts +++ b/src/app/core/interceptors/api.interceptor.ts @@ -1,6 +1,7 @@ import { HttpInterceptorFn } from '@angular/common/http'; +import { environment } from '../../../environments/environment'; export const apiInterceptor: HttpInterceptorFn = (req, next) => { - const apiReq = req.clone({ url: `https://api.realworld.show/api${req.url}` }); + const apiReq = req.clone({ url: `${environment.apiUrl}${req.url}` }); return next(apiReq); }; diff --git a/src/app/core/interceptors/error.interceptor.ts b/src/app/core/interceptors/error.interceptor.ts index b4cd8d84d..c53adb643 100644 --- a/src/app/core/interceptors/error.interceptor.ts +++ b/src/app/core/interceptors/error.interceptor.ts @@ -3,6 +3,7 @@ import { inject } from '@angular/core'; import { throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { UserService } from '../auth/services/user.service'; +import { Errors } from '../models/errors.model'; /** * Global HTTP error interceptor. @@ -27,6 +28,7 @@ import { UserService } from '../auth/services/user.service'; * Re-throws errors with { ...body, status } format so that: * - Components can access err.errors for display (e.g., validation errors) * - Auth logic can check err.status for error type decisions + * - Bodies without `errors` ({ message } or Spring Problem Details) keep their message * - Network errors get a user-friendly fallback message */ export const errorInterceptor: HttpInterceptorFn = (req, next) => { @@ -41,14 +43,21 @@ export const errorInterceptor: HttpInterceptorFn = (req, next) => { userService.purgeAuth(); } - // Normalize error format: { errors: {...}, status: number } - // Provides fallback message for network errors (status 0) or missing body - const body = - err.error && typeof err.error === 'object' && 'errors' in err.error - ? err.error - : { errors: { network: ['Unable to connect. Please check your internet connection.'] } }; - - return throwError(() => ({ ...body, status: err.status })); + return throwError(() => ({ ...normalizeErrorBody(err), status: err.status })); }), ); }; + +function normalizeErrorBody(err: HttpErrorResponse): Errors { + const body = err.error; + if (body && typeof body === 'object') { + if ('errors' in body) { + return body; + } + const message = body.message ?? body.detail ?? body.title ?? body.error; + if (typeof message === 'string' && message) { + return { errors: { '': [message] } }; + } + } + return { errors: { network: ['Unable to connect. Please check your internet connection.'] } }; +} diff --git a/src/app/core/models/errors.model.ts b/src/app/core/models/errors.model.ts index 8a5d017f4..641967634 100644 --- a/src/app/core/models/errors.model.ts +++ b/src/app/core/models/errors.model.ts @@ -1,3 +1,3 @@ export interface Errors { - errors: Record; + errors: Record; } diff --git a/src/app/features/article/services/articles.service.spec.ts b/src/app/features/article/services/articles.service.spec.ts index eff09a036..4bd695d43 100644 --- a/src/app/features/article/services/articles.service.spec.ts +++ b/src/app/features/article/services/articles.service.spec.ts @@ -200,7 +200,7 @@ describe('ArticlesService', () => { tagList: ['new', 'test'], }; const promise = firstValueFrom(service.create(newArticle)); - const req = httpMock.expectOne('/articles/'); + const req = httpMock.expectOne('/articles'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ article: newArticle }); req.flush({ article: { ...mockArticle, ...newArticle } }); @@ -216,7 +216,7 @@ describe('ArticlesService', () => { }; const errorResponse = { status: 422, statusText: 'Unprocessable Entity' }; const promise = firstValueFrom(service.create(invalidArticle)); - const req = httpMock.expectOne('/articles/'); + const req = httpMock.expectOne('/articles'); req.flush('Validation failed', errorResponse); await expect(promise).rejects.toMatchObject({ status: 422 }); }); diff --git a/src/app/features/article/services/articles.service.ts b/src/app/features/article/services/articles.service.ts index d102e162c..26576fddd 100644 --- a/src/app/features/article/services/articles.service.ts +++ b/src/app/features/article/services/articles.service.ts @@ -33,7 +33,7 @@ export class ArticlesService { } create(article: Partial
): Observable
{ - return this.http.post<{ article: Article }>('/articles/', { article: article }).pipe(map(data => data.article)); + return this.http.post<{ article: Article }>('/articles', { article: article }).pipe(map(data => data.article)); } update(article: Partial
): Observable
{ diff --git a/src/app/shared/components/list-errors.component.ts b/src/app/shared/components/list-errors.component.ts index ba3390eb0..0830163d2 100644 --- a/src/app/shared/components/list-errors.component.ts +++ b/src/app/shared/components/list-errors.component.ts @@ -10,6 +10,8 @@ export class ListErrorsComponent { errorList: string[] = []; @Input() set errors(errorList: Errors | null) { - this.errorList = errorList ? Object.keys(errorList.errors || {}).map(key => `${key} ${errorList.errors[key]}`) : []; + this.errorList = errorList + ? Object.keys(errorList.errors || {}).map(key => `${key} ${errorList.errors[key]}`.trim()) + : []; } } diff --git a/src/environments/environment.local.ts b/src/environments/environment.local.ts new file mode 100644 index 000000000..126cf4c8d --- /dev/null +++ b/src/environments/environment.local.ts @@ -0,0 +1,4 @@ +export const environment = { + production: false, + apiUrl: 'http://localhost:8080', +}; diff --git a/src/environments/environment.ts b/src/environments/environment.ts new file mode 100644 index 000000000..02a5c3fa4 --- /dev/null +++ b/src/environments/environment.ts @@ -0,0 +1,4 @@ +export const environment = { + production: true, + apiUrl: 'https://api.realworld.show/api', +}; From 0de77c53426a105fbfd6758d87ebf4bbe4a1c15c Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:41:09 +0000 Subject: [PATCH 2/2] fix: reload profile when the username route param changes --- .../components/profile-articles.component.ts | 9 ++++++--- .../components/profile-favorites.component.ts | 9 ++++++--- .../profile/pages/profile/profile.component.ts | 15 ++++++++++----- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/app/features/profile/components/profile-articles.component.ts b/src/app/features/profile/components/profile-articles.component.ts index 453ec2364..088b6b572 100644 --- a/src/app/features/profile/components/profile-articles.component.ts +++ b/src/app/features/profile/components/profile-articles.component.ts @@ -5,6 +5,7 @@ import { ProfileService } from '../services/profile.service'; import { Profile } from '../models/profile.model'; import { ArticleListConfig } from '../../article/models/article-list-config.model'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { switchMap } from 'rxjs/operators'; @Component({ selector: 'app-profile-articles', @@ -25,9 +26,11 @@ export default class ProfileArticlesComponent implements OnInit { ) {} ngOnInit(): void { - this.profileService - .get(this.route.snapshot.params['username']) - .pipe(takeUntilDestroyed(this.destroyRef)) + this.route.paramMap + .pipe( + switchMap(params => this.profileService.get(params.get('username')!)), + takeUntilDestroyed(this.destroyRef), + ) .subscribe({ next: (profile: Profile) => { this.profile.set(profile); diff --git a/src/app/features/profile/components/profile-favorites.component.ts b/src/app/features/profile/components/profile-favorites.component.ts index a48ee96f1..0f8565663 100644 --- a/src/app/features/profile/components/profile-favorites.component.ts +++ b/src/app/features/profile/components/profile-favorites.component.ts @@ -5,6 +5,7 @@ import { ProfileService } from '../services/profile.service'; import { Profile } from '../models/profile.model'; import { ArticleListConfig } from '../../article/models/article-list-config.model'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { switchMap } from 'rxjs/operators'; @Component({ selector: 'app-profile-favorites', @@ -25,9 +26,11 @@ export default class ProfileFavoritesComponent implements OnInit { ) {} ngOnInit() { - this.profileService - .get(this.route.parent?.snapshot.params['username']) - .pipe(takeUntilDestroyed(this.destroyRef)) + this.route + .parent!.paramMap.pipe( + switchMap(params => this.profileService.get(params.get('username')!)), + takeUntilDestroyed(this.destroyRef), + ) .subscribe({ next: (profile: Profile) => { this.profile.set(profile); diff --git a/src/app/features/profile/pages/profile/profile.component.ts b/src/app/features/profile/pages/profile/profile.component.ts index 82d89196c..79a8b7443 100644 --- a/src/app/features/profile/pages/profile/profile.component.ts +++ b/src/app/features/profile/pages/profile/profile.component.ts @@ -39,12 +39,17 @@ export class ProfileComponent implements OnInit { ) {} ngOnInit() { - this.profileService - .get(this.route.snapshot.params['username']) + this.route.paramMap .pipe( - catchError(error => { - this.errors.set(error.errors || { error: ['Failed to load profile'] }); - return EMPTY; + switchMap(params => { + this.profile.set(null); + this.errors.set(null); + return this.profileService.get(params.get('username')!).pipe( + catchError(error => { + this.errors.set(error.errors || { error: ['Failed to load profile'] }); + return EMPTY; + }), + ); }), switchMap(profile => { return combineLatest([of(profile), this.userService.currentUser]);