Refactor logging in IcaRecipeParser and QuickImportService to use NestJS Logger
- Updated IcaRecipeParser to replace console.log statements with Logger for better logging practices. - Enhanced QuickImportService with Logger for consistent logging and error handling. - Changed quantity validation in CreateRecipeIngredientDto and CreateRecipeDto to allow zero. - Removed CanonicalNameForm and NameForm components from the frontend. - Updated EditProductForm to use a select dropdown for categories instead of a text input. - Added validation for product name, canonical name, and category length in product update action. - Refactored unit options into a separate file for better reusability across components. - Removed unused API fetching functions and inventory types to clean up the codebase.
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { RecipeParser, ParsedRecipe } from './base.parser';
|
||||
|
||||
/**
|
||||
@@ -6,13 +7,14 @@ import { RecipeParser, ParsedRecipe } from './base.parser';
|
||||
* Denna är mer permissiv än site-specifika parsers
|
||||
*/
|
||||
export class GenericRecipeParser extends RecipeParser {
|
||||
private readonly logger = new Logger(GenericRecipeParser.name);
|
||||
canHandle(url: string): boolean {
|
||||
// Denna parser hanterar alltid (är fallback)
|
||||
return true;
|
||||
}
|
||||
|
||||
parse(html: string): ParsedRecipe {
|
||||
console.log('[GenericParser] Parsing recipe from unknown site...');
|
||||
this.logger.log('Parsing recipe from unknown site...');
|
||||
|
||||
// Extrahera og:image för bildurl-fallback
|
||||
const ogImage = this.extractOgImage(html);
|
||||
@@ -31,15 +33,15 @@ export class GenericRecipeParser extends RecipeParser {
|
||||
: jsonData['@graph']?.find((item: any) => item['@type'] === 'Recipe');
|
||||
|
||||
if (recipe) {
|
||||
console.log('[GenericParser] ✓ JSON-LD data found');
|
||||
this.logger.log('JSON-LD data found');
|
||||
return this.extractFromJsonLd(recipe, ogImage);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('[GenericParser] JSON-LD parsing failed');
|
||||
this.logger.warn('JSON-LD parsing failed');
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[GenericParser] No JSON-LD found, using HTML parsing');
|
||||
this.logger.log('No JSON-LD found, using HTML parsing');
|
||||
return this.parseFromHtml(html, ogImage);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { RecipeParser, ParsedRecipe } from './base.parser';
|
||||
|
||||
/**
|
||||
@@ -5,12 +6,13 @@ import { RecipeParser, ParsedRecipe } from './base.parser';
|
||||
* Använder JSON-LD structured data som primär källa
|
||||
*/
|
||||
export class IcaRecipeParser extends RecipeParser {
|
||||
private readonly logger = new Logger(IcaRecipeParser.name);
|
||||
canHandle(url: string): boolean {
|
||||
return /ica\.se\/recept/i.test(url);
|
||||
}
|
||||
|
||||
parse(html: string): ParsedRecipe {
|
||||
console.log('[IcaParser] Parsing ICA recipe...');
|
||||
this.logger.log('Parsing ICA recipe...');
|
||||
|
||||
// Extrahera og:image för bildurl-fallback
|
||||
const ogImage = this.extractOgImage(html);
|
||||
@@ -31,16 +33,16 @@ export class IcaRecipeParser extends RecipeParser {
|
||||
: jsonData['@graph']?.find((item: any) => item['@type'] === 'Recipe');
|
||||
|
||||
if (recipe) {
|
||||
console.log('[IcaParser] ✓ JSON-LD recipe found');
|
||||
this.logger.log('JSON-LD recipe found');
|
||||
return this.extractFromJsonLd(recipe, ogImage);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('[IcaParser] JSON-LD parsing failed:', err);
|
||||
this.logger.warn(`JSON-LD parsing failed: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: HTML parsing (sällan nödvändigt för ICA)
|
||||
console.log('[IcaParser] Falling back to HTML parsing');
|
||||
this.logger.log('Falling back to HTML parsing');
|
||||
return this.parseFromHtml(html, ogImage);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
Logger,
|
||||
ServiceUnavailableException,
|
||||
UnsupportedMediaTypeException,
|
||||
} from '@nestjs/common';
|
||||
@@ -25,24 +26,26 @@ type UploadKind = 'pdf' | 'image';
|
||||
|
||||
@Injectable()
|
||||
export class QuickImportService {
|
||||
private readonly logger = new Logger(QuickImportService.name);
|
||||
|
||||
/**
|
||||
* Detekterar typ av input (URL eller filsökväg) och importerar från lämplig källa
|
||||
*/
|
||||
async importFromInput(input: string): Promise<QuickImportResult> {
|
||||
const trimmed = input.trim();
|
||||
console.log('[QuickImport] Mottog input:', trimmed);
|
||||
this.logger.log(`Mottog input: ${trimmed}`);
|
||||
|
||||
if (!trimmed) {
|
||||
throw new BadRequestException('Du måste ange en URL eller ladda upp en fil');
|
||||
}
|
||||
|
||||
if (this.isUrl(trimmed)) {
|
||||
console.log('[QuickImport] Detekterade URL, försöker scrapa...');
|
||||
this.logger.log('Detekterade URL, försöker scrapa...');
|
||||
return this.scrapeRecipeFromUrl(trimmed);
|
||||
}
|
||||
|
||||
if (this.looksLikeLocalFile(trimmed)) {
|
||||
console.log('[QuickImport] Försöker läsa lokal fil:', trimmed);
|
||||
this.logger.log(`Försöker läsa lokal fil: ${trimmed}`);
|
||||
try {
|
||||
const buffer = await fs.readFile(trimmed);
|
||||
return this.importFromUpload({
|
||||
@@ -51,7 +54,7 @@ export class QuickImportService {
|
||||
mimetype: this.getMimeTypeFromExtension(trimmed),
|
||||
} as Express.Multer.File);
|
||||
} catch (error) {
|
||||
console.error('[QuickImport] Kunde inte läsa lokal fil:', error);
|
||||
this.logger.error('Kunde inte läsa lokal fil:', error);
|
||||
throw new BadRequestException(
|
||||
'Kunde inte läsa filen. Använd filuppladdning i gränssnittet eller kontrollera sökvägen.',
|
||||
);
|
||||
@@ -68,7 +71,7 @@ export class QuickImportService {
|
||||
throw new BadRequestException('Ingen fil skickades med.');
|
||||
}
|
||||
|
||||
console.log('[QuickImport] Mottog uppladdad fil:', file.originalname, file.mimetype);
|
||||
this.logger.log(`Mottog uppladdad fil: ${file.originalname} (${file.mimetype})`);
|
||||
const kind = this.getUploadKind(file);
|
||||
|
||||
if (kind === 'pdf') {
|
||||
@@ -154,7 +157,7 @@ export class QuickImportService {
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.error('[QuickImport] PDF ERROR:', error);
|
||||
this.logger.error('PDF-import misslyckades', error);
|
||||
throw new ServiceUnavailableException('PDF-importen misslyckades.');
|
||||
}
|
||||
}
|
||||
@@ -176,7 +179,7 @@ export class QuickImportService {
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.error('[QuickImport] OCR ERROR:', error);
|
||||
this.logger.error('OCR-import misslyckades', error);
|
||||
throw new ServiceUnavailableException('OCR-importen misslyckades.');
|
||||
} finally {
|
||||
await worker.terminate();
|
||||
@@ -262,7 +265,7 @@ export class QuickImportService {
|
||||
*/
|
||||
private async scrapeRecipeFromUrl(url: string): Promise<QuickImportResult> {
|
||||
try {
|
||||
console.log('[QuickImport] Hämtar HTML från:', url);
|
||||
this.logger.log(`Hämtar HTML från: ${url}`);
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
@@ -271,14 +274,14 @@ export class QuickImportService {
|
||||
},
|
||||
});
|
||||
|
||||
console.log('[QuickImport] HTTP status:', response.status);
|
||||
this.logger.log(`HTTP status: ${response.status}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
console.log('[QuickImport] HTML längd:', html.length, 'tecken');
|
||||
this.logger.log(`HTML längd: ${html.length} tecken`);
|
||||
|
||||
const parsers: RecipeParser[] = [
|
||||
new IcaRecipeParser(),
|
||||
@@ -288,7 +291,7 @@ export class QuickImportService {
|
||||
let recipe = null;
|
||||
for (const parser of parsers) {
|
||||
if (parser.canHandle(url)) {
|
||||
console.log('[QuickImport] Använder parser:', parser.constructor.name);
|
||||
this.logger.log(`Använder parser: ${parser.constructor.name}`);
|
||||
recipe = parser.parse(html);
|
||||
break;
|
||||
}
|
||||
@@ -298,17 +301,14 @@ export class QuickImportService {
|
||||
throw new Error('Ingen parserutrustning tillgänglig');
|
||||
}
|
||||
|
||||
console.log('[QuickImport] Parsad recept:', {
|
||||
name: recipe.name,
|
||||
ingredienser: recipe.ingredients.length,
|
||||
});
|
||||
this.logger.log(`Parsad recept: ${recipe.name} (${recipe.ingredients.length} ingredienser)`);
|
||||
|
||||
if (!recipe.name) {
|
||||
throw new Error('Kunde inte hitta receptnamn på sidan. Försök med en annan länk.');
|
||||
}
|
||||
|
||||
const markdown = this.recipeToMarkdown(recipe, url);
|
||||
console.log('[QuickImport] Markdown genererad, längd:', markdown.length);
|
||||
this.logger.log(`Markdown genererad, längd: ${markdown.length}`);
|
||||
|
||||
let source: 'ica' | 'pdf' | 'image' | 'other' = 'other';
|
||||
if (/ica\.se/i.test(url)) {
|
||||
@@ -320,9 +320,9 @@ export class QuickImportService {
|
||||
if (recipe.imageUrl) {
|
||||
try {
|
||||
imageUrl = await downloadAndOptimizeImage(recipe.imageUrl, IMAGE_DEST_DIR);
|
||||
console.log('[QuickImport] Bild optimerad och sparad:', imageUrl);
|
||||
this.logger.log(`Bild optimerad och sparad: ${imageUrl}`);
|
||||
} catch (imgErr) {
|
||||
console.warn('[QuickImport] Kunde inte ladda ner bild:', imgErr);
|
||||
this.logger.warn(`Kunde inte ladda ner bild: ${imgErr}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,7 +333,7 @@ export class QuickImportService {
|
||||
};
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Okänt fel vid scraping';
|
||||
console.error('[QuickImport] ERROR:', message);
|
||||
this.logger.error(`Scraping misslyckades: ${message}`);
|
||||
throw new BadRequestException(
|
||||
`Kunde inte hämta recept: ${message}. Kontrollera att länken är korrekt och försök igen.`
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user