Skip to content
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -69,6 +81,9 @@
},
"development": {
"buildTarget": "angular-conduit:build:development"
},
"local": {
"buildTarget": "angular-conduit:build:local"
}
},
"defaultConfiguration": "development"
Expand Down
2 changes: 1 addition & 1 deletion e2e/error-handling.spec.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion e2e/health.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
2 changes: 1 addition & 1 deletion e2e/helpers/api.ts
Original file line number Diff line number Diff line change
@@ -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';

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Automatic E2E startup uses public backend

Without an existing frontend server, setting API_URL changes helpers and mocks but leaves browser requests targeting the public API. The webServer configuration launches npm run start, which selects the default environment. Local E2E execution therefore requires a separately running start:local server.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.


export interface UserCredentials {
email: string;
Expand Down
2 changes: 1 addition & 1 deletion e2e/settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion e2e/user-fetch-errors.spec.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
84 changes: 84 additions & 0 deletions scripts/seed-local.ts
Original file line number Diff line number Diff line change
@@ -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'];
Comment on lines +8 to +9

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👁️ TD Information Security: Published credentials for seeded accounts

Running seed:local gives jake, ana, and sam a repository-published PASSWORD, allowing anyone reaching that backend to impersonate them. The seeding summary also logs it. This violates Secrets and configuration; the demo exemption covers only gitignored local environment files.

View in Devin Review · Custom reviewer

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

const TAGS = ['angular', 'spring', 'java', 'rxjs', 'testing'];
const ARTICLES_PER_USER = 9;

async function call<T>(method: string, path: string, body?: unknown, token?: string): Promise<T> {
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<string> {
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<void> {
const tokens: Record<string, string> = {};
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);
});
3 changes: 2 additions & 1 deletion src/app/core/interceptors/api.interceptor.ts
Original file line number Diff line number Diff line change
@@ -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);
};
25 changes: 17 additions & 8 deletions src/app/core/interceptors/error.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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) => {
Expand All @@ -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.'] } };
}
2 changes: 1 addition & 1 deletion src/app/core/models/errors.model.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export interface Errors {
errors: Record<string, string>;
errors: Record<string, string | string[]>;
}
4 changes: 2 additions & 2 deletions src/app/features/article/services/articles.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } });
Expand All @@ -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 });
});
Expand Down
2 changes: 1 addition & 1 deletion src/app/features/article/services/articles.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class ArticlesService {
}

create(article: Partial<Article>): Observable<Article> {
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));

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Remaining mocks miss revised endpoints

After this change, the creation network-error mock still matches /articles/, so create() bypasses its simulated failure. With the local backend, article deletion and comment deletion mocks also miss requests because they require /api. Those deletion tests can pass without exercising mocked 200 responses.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}

update(article: Partial<Article>): Observable<Article> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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);
Expand Down
15 changes: 10 additions & 5 deletions src/app/features/profile/pages/profile/profile.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
4 changes: 3 additions & 1 deletion src/app/shared/components/list-errors.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())
: [];
}
}
4 changes: 4 additions & 0 deletions src/environments/environment.local.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const environment = {
production: false,
apiUrl: 'http://localhost:8080',
};
4 changes: 4 additions & 0 deletions src/environments/environment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const environment = {
production: true,
apiUrl: 'https://api.realworld.show/api',
};
Loading