From 125956eb3e781ce8f8c148b20f8f9a2bb75f5eff Mon Sep 17 00:00:00 2001 From: Thomas <4159106+dtslvr@users.noreply.github.com> Date: Sun, 25 Apr 2021 12:11:52 +0200 Subject: [PATCH] Refactor number extraction from string (#41) --- .../ghostfolio-scraper-api.service.ts | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/apps/api/src/services/data-provider/ghostfolio-scraper-api/ghostfolio-scraper-api.service.ts b/apps/api/src/services/data-provider/ghostfolio-scraper-api/ghostfolio-scraper-api.service.ts index 1b0d6ba47..7b5fba378 100644 --- a/apps/api/src/services/data-provider/ghostfolio-scraper-api/ghostfolio-scraper-api.service.ts +++ b/apps/api/src/services/data-provider/ghostfolio-scraper-api/ghostfolio-scraper-api.service.ts @@ -15,6 +15,8 @@ import { PrismaService } from '../../prisma.service'; @Injectable() export class GhostfolioScraperApiService implements DataProviderInterface { + private static NUMERIC_REGEXP = /[-]{0,1}[\d]*[.,]{0,1}[\d]+/g; + public constructor(private prisma: PrismaService) {} public async get( @@ -75,12 +77,9 @@ export class GhostfolioScraperApiService implements DataProviderInterface { const html = await get(); const $ = cheerio.load(html); - const string = $(scraperConfig?.selector) - .text() - .replace('CHF', '') - .trim(); - - const value = parseFloat(string); + const value = this.extractNumberFromString( + $(scraperConfig?.selector).text() + ); return { [symbol]: { @@ -96,6 +95,17 @@ export class GhostfolioScraperApiService implements DataProviderInterface { return {}; } + private extractNumberFromString(aString: string): number { + try { + const [numberString] = aString.match( + GhostfolioScraperApiService.NUMERIC_REGEXP + ); + return parseFloat(numberString.trim()); + } catch { + return undefined; + } + } + private async getScraperConfig(aSymbol: string) { try { const {