Browse Source

Task/improve type safety in symbol and benchmark services (#8404)

Improve type safety
pull/8374/head^2
Kenrick Tandrian 3 weeks ago
committed by GitHub
parent
commit
22ddbbbda7
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 29
      apps/api/src/services/benchmark/benchmark.service.ts
  2. 85
      apps/api/src/services/symbol-profile/symbol-profile.service.spec.ts
  3. 34
      apps/api/src/services/symbol-profile/symbol-profile.service.ts
  4. 8
      apps/api/src/services/symbol/symbol.service.ts

29
apps/api/src/services/benchmark/benchmark.service.ts

@ -16,7 +16,8 @@ import {
AssetProfileIdentifier, AssetProfileIdentifier,
Benchmark, Benchmark,
BenchmarkProperty, BenchmarkProperty,
BenchmarkResponse BenchmarkResponse,
EnhancedAssetProfile
} from '@ghostfolio/common/interfaces'; } from '@ghostfolio/common/interfaces';
import { Injectable, Logger } from '@nestjs/common'; import { Injectable, Logger } from '@nestjs/common';
@ -88,18 +89,20 @@ export class BenchmarkService {
this.CACHE_KEY_BENCHMARKS this.CACHE_KEY_BENCHMARKS
); );
const { benchmarks, expiration }: BenchmarkValue = if (cachedBenchmarkValue) {
JSON.parse(cachedBenchmarkValue); const { benchmarks, expiration }: BenchmarkValue =
JSON.parse(cachedBenchmarkValue);
this.logger.debug('Fetched benchmarks from cache'); this.logger.debug('Fetched benchmarks from cache');
if (isPast(new Date(expiration))) { if (isPast(new Date(expiration))) {
this.calculateAndCacheBenchmarks({ this.calculateAndCacheBenchmarks({
enableSharing enableSharing
}); });
} }
return benchmarks; return benchmarks;
}
} catch {} } catch {}
} }
@ -108,7 +111,9 @@ export class BenchmarkService {
public async getBenchmarkAssetProfiles({ public async getBenchmarkAssetProfiles({
enableSharing = false enableSharing = false
} = {}): Promise<Partial<SymbolProfile>[]> { } = {}): Promise<
Pick<EnhancedAssetProfile, 'dataSource' | 'id' | 'name' | 'symbol'>[]
> {
const symbolProfileIds: string[] = ( const symbolProfileIds: string[] = (
(await this.propertyService.getByKey<BenchmarkProperty[]>( (await this.propertyService.getByKey<BenchmarkProperty[]>(
PROPERTY_BENCHMARKS PROPERTY_BENCHMARKS
@ -293,7 +298,7 @@ export class BenchmarkService {
name: benchmarkAssetProfiles[index].name, name: benchmarkAssetProfiles[index].name,
performances: { performances: {
allTimeHigh: { allTimeHigh: {
date: allTimeHigh?.date, date: allTimeHigh?.date as Date,
performancePercent: this.getPerformancePercentFromAllTimeHigh( performancePercent: this.getPerformancePercentFromAllTimeHigh(
performancePercentFromAllTimeHigh performancePercentFromAllTimeHigh
) )

85
apps/api/src/services/symbol-profile/symbol-profile.service.spec.ts

@ -81,4 +81,89 @@ describe('SymbolProfileService', () => {
).resolves.toEqual([expect.objectContaining({ name: 'Apple' })]); ).resolves.toEqual([expect.objectContaining({ name: 'Apple' })]);
}); });
}); });
describe('getSymbolProfiles', () => {
let findManySymbolProfiles: jest.Mock;
let symbolProfileService: SymbolProfileService;
beforeEach(() => {
findManySymbolProfiles = jest.fn();
symbolProfileService = new SymbolProfileService({
symbolProfile: { findMany: findManySymbolProfiles }
} as unknown as PrismaService);
});
it('enhances the symbol profile and excludes relational metadata', async () => {
const dateOfFirstActivity = new Date('2024-01-15T00:00:00.000Z');
findManySymbolProfiles.mockResolvedValue([
{
_count: { activities: 3, watchedBy: 1 },
activities: [{ date: dateOfFirstActivity }],
assetProfileOverrides: { name: 'Apple Inc. (Custom)' },
currency: 'USD',
dataSource: DataSource.YAHOO,
isin: 'US0378331005',
name: 'Apple Inc.',
scraperConfiguration: {
defaultMarketPrice: 100,
headers: { 'User-Agent': 'Test' },
locale: 'en',
mode: 'lazy',
selector: '.price',
url: 'https://example.com'
},
symbol: 'AAPL'
}
]);
const [result] = await symbolProfileService.getSymbolProfiles([
{ dataSource: DataSource.YAHOO, symbol: 'AAPL' }
]);
expect(result).toEqual(
expect.objectContaining({
activitiesCount: 3,
dateOfFirstActivity,
name: 'Apple Inc. (Custom)',
scraperConfiguration: {
defaultMarketPrice: 100,
headers: { 'User-Agent': 'Test' },
locale: 'en',
mode: 'lazy',
selector: '.price',
url: 'https://example.com'
},
watchedByCount: 1
})
);
expect(result).not.toHaveProperty('_count');
expect(result).not.toHaveProperty('activities');
expect(result).not.toHaveProperty('assetProfileOverrides');
});
it('gives null for scraperConfiguration if none exists', async () => {
findManySymbolProfiles.mockResolvedValue([
{
_count: { activities: 0 },
assetProfileOverrides: null,
currency: 'USD',
dataSource: DataSource.YAHOO,
isin: 'US0378331005',
name: 'Apple Inc.',
scraperConfiguration: null,
symbol: 'AAPL'
}
]);
const [result] = await symbolProfileService.getSymbolProfiles([
{ dataSource: DataSource.YAHOO, symbol: 'AAPL' }
]);
expect(result.scraperConfiguration).toBeNull();
expect(result.dateOfFirstActivity).toBeUndefined();
expect(result.watchedByCount).toBe(0);
});
});
}); });

34
apps/api/src/services/symbol-profile/symbol-profile.service.ts

@ -21,6 +21,7 @@ import {
SymbolProfile SymbolProfile
} from '@prisma/client'; } from '@prisma/client';
import { continents, countries } from 'countries-list'; import { continents, countries } from 'countries-list';
import { omit } from 'lodash-es';
@Injectable() @Injectable()
export class SymbolProfileService { export class SymbolProfileService {
@ -284,7 +285,7 @@ export class SymbolProfileService {
activities?: { activities?: {
date: Date; date: Date;
}[]; }[];
assetProfileOverrides: AssetProfileOverrides; assetProfileOverrides: AssetProfileOverrides | null;
})[] })[]
): EnhancedAssetProfile[] { ): EnhancedAssetProfile[] {
return symbolProfiles.map((symbolProfile) => { return symbolProfiles.map((symbolProfile) => {
@ -293,13 +294,19 @@ export class SymbolProfileService {
symbolProfile.assetProfileOverrides symbolProfile.assetProfileOverrides
); );
const item = { const symbolProfileWithoutExtras = omit(symbolProfileWithOverrides, [
...symbolProfileWithOverrides, '_count',
activitiesCount: 0, 'activities',
'assetProfileOverrides'
]);
return {
...symbolProfileWithoutExtras,
activitiesCount: symbolProfile._count.activities,
countries: this.getCountries( countries: this.getCountries(
symbolProfileWithOverrides?.countries as unknown as Prisma.JsonArray symbolProfileWithOverrides?.countries as unknown as Prisma.JsonArray
), ),
dateOfFirstActivity: undefined as Date, dateOfFirstActivity: symbolProfile.activities?.[0]?.date,
holdings: this.getHoldings( holdings: this.getHoldings(
symbolProfileWithOverrides?.holdings as unknown as Prisma.JsonArray symbolProfileWithOverrides?.holdings as unknown as Prisma.JsonArray
), ),
@ -310,19 +317,8 @@ export class SymbolProfileService {
symbolProfileWithOverrides?.sectors as unknown as Prisma.JsonArray symbolProfileWithOverrides?.sectors as unknown as Prisma.JsonArray
), ),
symbolMapping: this.getSymbolMapping(symbolProfileWithOverrides), symbolMapping: this.getSymbolMapping(symbolProfileWithOverrides),
watchedByCount: 0 watchedByCount: symbolProfile._count.watchedBy ?? 0
}; } as EnhancedAssetProfile;
item.activitiesCount = symbolProfile._count.activities;
item.watchedByCount = symbolProfile._count.watchedBy ?? 0;
delete item._count;
item.dateOfFirstActivity = symbolProfile.activities?.[0]?.date;
delete item.activities;
delete item.assetProfileOverrides;
return item;
}); });
} }
@ -361,7 +357,7 @@ export class SymbolProfileService {
private getScraperConfiguration( private getScraperConfiguration(
symbolProfile: SymbolProfile symbolProfile: SymbolProfile
): ScraperConfiguration { ): ScraperConfiguration | null {
const scraperConfiguration = const scraperConfiguration =
symbolProfile.scraperConfiguration as Prisma.JsonObject; symbolProfile.scraperConfiguration as Prisma.JsonObject;

8
apps/api/src/services/symbol/symbol.service.ts

@ -40,7 +40,7 @@ export class SymbolService {
dataGatheringItem: DataGatheringItem; dataGatheringItem: DataGatheringItem;
includeHistoricalData?: number; includeHistoricalData?: number;
useIntradayData?: boolean; useIntradayData?: boolean;
}): Promise<SymbolItem> { }): Promise<SymbolItem | undefined> {
let currency: string; let currency: string;
let marketPrice: number; let marketPrice: number;
@ -63,7 +63,7 @@ export class SymbolService {
if (dataGatheringItem.dataSource && marketPrice >= 0) { if (dataGatheringItem.dataSource && marketPrice >= 0) {
let historicalData: HistoricalDataItem[] = []; let historicalData: HistoricalDataItem[] = [];
if (includeHistoricalData > 0) { if (includeHistoricalData && includeHistoricalData > 0) {
const days = includeHistoricalData; const days = includeHistoricalData;
const marketData = await this.marketDataService.getRange({ const marketData = await this.marketDataService.getRange({
@ -168,10 +168,10 @@ export class SymbolService {
fearAndGreedIndex: { fearAndGreedIndex: {
CRYPTOCURRENCIES: { CRYPTOCURRENCIES: {
...marketDataFearAndGreedIndexCryptocurrencies ...marketDataFearAndGreedIndexCryptocurrencies
}, } as SymbolItem,
STOCKS: { STOCKS: {
...marketDataFearAndGreedIndexStocks ...marketDataFearAndGreedIndexStocks
} } as SymbolItem
} }
}; };
} }

Loading…
Cancel
Save