fix(metadata): refactor book metadata fetching to use fetch API and signals for state management (#495)
* fix(metadata): refactor book metadata fetching to use fetch API and signals for state management * fix(metadata): update tests to mock fetch API for book metadata streaming * fix(metadata): improve metadata fetching with error handling and retry logic * fix(metadata): update author photo search to use SSE with auth headers and improve error handling * fix(metadata): require bookId for cover fetching and improve error handling * fix(metadata): simplify error handling in DuckDuckGo cover image fetching * fix(metadata): refactor SSE data handling for cover image and book metadata fetching
This commit is contained in:
@@ -1,53 +1,85 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookCoverService, CoverFetchRequest, CoverImage} from './book-cover.service';
|
||||
import {AuthService} from '../service/auth.service';
|
||||
|
||||
describe('BookCoverService', () => {
|
||||
let service: BookCoverService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: {getInternalAccessToken: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(() => {
|
||||
authService = {
|
||||
getInternalAccessToken: vi.fn(() => 'token-123'),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookCoverService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookCoverService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('posts the cover fetch request and returns the backend response', () => {
|
||||
it('streams covers over SSE with auth headers', async () => {
|
||||
const requestBody: CoverFetchRequest = {
|
||||
bookId: 123,
|
||||
title: 'Dune',
|
||||
author: 'Frank Herbert',
|
||||
coverType: 'ebook',
|
||||
};
|
||||
const response: CoverImage[] = [
|
||||
{url: 'https://example.test/cover-1.jpg', source: 'google', width: 600, height: 900, index: 0},
|
||||
{url: 'https://example.test/cover-2.jpg', source: 'openlibrary', index: 1},
|
||||
];
|
||||
const mockImage = {url: 'https://example.test/cover-1.jpg', index: 1};
|
||||
const encoder = new TextEncoder();
|
||||
const dataChunk = encoder.encode(`data: ${JSON.stringify(mockImage)}\n`);
|
||||
|
||||
let result: CoverImage[] | undefined;
|
||||
const mockReader = {
|
||||
read: vi.fn()
|
||||
.mockResolvedValueOnce({done: false, value: dataChunk})
|
||||
.mockResolvedValueOnce({done: true, value: undefined}),
|
||||
releaseLock: vi.fn()
|
||||
};
|
||||
|
||||
const mockResponse = {
|
||||
ok: true,
|
||||
body: {
|
||||
getReader: () => mockReader
|
||||
}
|
||||
};
|
||||
|
||||
const fetchSpy = vi.fn().mockResolvedValue(mockResponse);
|
||||
vi.stubGlobal('fetch', fetchSpy);
|
||||
|
||||
let result: CoverImage | undefined;
|
||||
service.fetchBookCovers(requestBody).subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/1/metadata/covers'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(requestBody);
|
||||
request.flush(response);
|
||||
// Wait for the stream to process
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
expect(result).toEqual(response);
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/api\/v1\/books\/123\/metadata\/covers$/),
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer token-123'
|
||||
},
|
||||
body: JSON.stringify(requestBody)
|
||||
})
|
||||
);
|
||||
expect(result).toEqual(mockImage);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {AuthService} from '../service/auth.service';
|
||||
|
||||
export interface CoverImage {
|
||||
url: string;
|
||||
@@ -12,6 +13,7 @@ export interface CoverImage {
|
||||
}
|
||||
|
||||
export interface CoverFetchRequest {
|
||||
bookId?: number;
|
||||
title?: string;
|
||||
author?: string;
|
||||
coverType?: 'ebook' | 'audiobook';
|
||||
@@ -24,9 +26,98 @@ export class BookCoverService {
|
||||
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
fetchBookCovers(request: CoverFetchRequest): Observable<CoverImage[]> {
|
||||
return this.http.post<CoverImage[]>(`${this.baseUrl}/1/metadata/covers`, request);
|
||||
fetchBookCovers(request: CoverFetchRequest): Observable<CoverImage> {
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
|
||||
return new Observable<CoverImage>(subscriber => {
|
||||
if (!request.bookId) {
|
||||
subscriber.error(new Error('bookId is required for fetching covers'));
|
||||
return;
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
|
||||
fetch(`${this.baseUrl}/${request.bookId}/metadata/covers`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(request),
|
||||
signal: abortController.signal
|
||||
})
|
||||
.then(async response => {
|
||||
if (!response.ok) {
|
||||
subscriber.error(new Error(`HTTP error! status: ${response.status}`));
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) {
|
||||
subscriber.error(new Error('Response body is null'));
|
||||
return;
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
const emitLine = (line: string) => {
|
||||
if (!line.startsWith('data:')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = line.slice(5).trim();
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const image = JSON.parse(data) as CoverImage;
|
||||
subscriber.next(image);
|
||||
} catch (e) {
|
||||
console.error('Error parsing SSE data:', e);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, {stream: true});
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
emitLine(line);
|
||||
}
|
||||
}
|
||||
if (buffer) {
|
||||
emitLine(buffer);
|
||||
}
|
||||
subscriber.complete();
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
// Silently handle abort
|
||||
} else {
|
||||
subscriber.error(error);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return;
|
||||
}
|
||||
subscriber.error(error);
|
||||
});
|
||||
|
||||
return () => {
|
||||
abortController.abort();
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user