Browse Source

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

Improve type safety
pull/8374/head^2
Kenrick Tandrian 2 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,
Benchmark,
BenchmarkProperty,
BenchmarkResponse
BenchmarkResponse,
EnhancedAssetProfile
} from '@ghostfolio/common/interfaces';
import { Injectable, Logger } from '@nestjs/common';
@ -88,18 +89,20 @@ export class BenchmarkService {
this.CACHE_KEY_BENCHMARKS
);
const { benchmarks, expiration }: BenchmarkValue =
JSON.parse(cachedBenchmarkValue);
if (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))) {
this.calculateAndCacheBenchmarks({
enableSharing
});
}
if (isPast(new Date(expiration))) {
this.calculateAndCacheBenchmarks({
enableSharing
});
}
return benchmarks;
return benchmarks;
}
} catch {}
}
@ -108,7 +111,9 @@ export class BenchmarkService {
public async getBenchmarkAssetProfiles({
enableSharing = false
} = {}): Promise<Partial<SymbolProfile>[]> {
} = {}): Promise<
Pick<EnhancedAssetProfile, 'dataSource' | 'id' | 'name' | 'symbol'>[]
> {
const symbolProfileIds: string[] = (
(await this.propertyService.getByKey<BenchmarkProperty[]>(
PROPERTY_BENCHMARKS
@ -293,7 +298,7 @@ export class BenchmarkService {
name: benchmarkAssetProfiles[index].name,
performances: {
allTimeHigh: {
date: allTimeHigh?.date,
date: allTimeHigh?.date as Date,
performancePercent: this.getPerformancePercentFromAllTimeHigh(
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' })]);
});
});
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
} from '@prisma/client';
import { continents, countries } from 'countries-list';
import { omit } from 'lodash-es';
@Injectable()
export class SymbolProfileService {
@ -284,7 +285,7 @@ export class SymbolProfileService {
activities?: {
date: Date;
}[];
assetProfileOverrides: AssetProfileOverrides;
assetProfileOverrides: AssetProfileOverrides | null;
})[]
): EnhancedAssetProfile[] {
return symbolProfiles.map((symbolProfile) => {
@ -293,13 +294,19 @@ export class SymbolProfileService {
symbolProfile.assetProfileOverrides
);
const item = {
...symbolProfileWithOverrides,
activitiesCount: 0,
const symbolProfileWithoutExtras = omit(symbolProfileWithOverrides, [
'_count',
'activities',
'assetProfileOverrides'
]);
return {
...symbolProfileWithoutExtras,
activitiesCount: symbolProfile._count.activities,
countries: this.getCountries(
symbolProfileWithOverrides?.countries as unknown as Prisma.JsonArray
),
dateOfFirstActivity: undefined as Date,
dateOfFirstActivity: symbolProfile.activities?.[0]?.date,
holdings: this.getHoldings(
symbolProfileWithOverrides?.holdings as unknown as Prisma.JsonArray
),
@ -310,19 +317,8 @@ export class SymbolProfileService {
symbolProfileWithOverrides?.sectors as unknown as Prisma.JsonArray
),
symbolMapping: this.getSymbolMapping(symbolProfileWithOverrides),
watchedByCount: 0
};
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;
watchedByCount: symbolProfile._count.watchedBy ?? 0
} as EnhancedAssetProfile;
});
}
@ -361,7 +357,7 @@ export class SymbolProfileService {
private getScraperConfiguration(
symbolProfile: SymbolProfile
): ScraperConfiguration {
): ScraperConfiguration | null {
const scraperConfiguration =
symbolProfile.scraperConfiguration as Prisma.JsonObject;

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

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

Loading…
Cancel
Save