Browse Source

Improve validation of Trackinsight holdings

pull/8360/head
Thomas Kaul 4 weeks ago
parent
commit
b7d1158eb9
  1. 105
      apps/api/src/services/data-provider/data-enhancer/trackinsight/trackinsight.service.spec.ts
  2. 37
      apps/api/src/services/data-provider/data-enhancer/trackinsight/trackinsight.service.ts

105
apps/api/src/services/data-provider/data-enhancer/trackinsight/trackinsight.service.spec.ts

@ -1,3 +1,5 @@
import { Logger } from '@nestjs/common';
import { TrackinsightDataEnhancerService } from './trackinsight.service'; import { TrackinsightDataEnhancerService } from './trackinsight.service';
jest.mock('@ghostfolio/api/services/fetch/fetch.service', () => { jest.mock('@ghostfolio/api/services/fetch/fetch.service', () => {
@ -163,6 +165,52 @@ describe('TrackinsightDataEnhancerService', () => {
expect(fetchService.fetch).toHaveBeenCalledTimes(1); expect(fetchService.fetch).toHaveBeenCalledTimes(1);
}); });
it.each([
['a single result', 1, 'QQQ.US'],
['an exact match', 2, 'QQQ'],
['a match with an exchange', 2, 'XETRA:QQQ']
])('should use the ticker of %s in the search', async (_, count, ticker) => {
mockResponses({
search: Response.json({ results: { count, docs: [{ ticker }] } })
});
await enhance();
expect(fetchService.fetch.mock.calls[1][0]).toContain(
`/data-api/funds/${ticker}.json`
);
});
it('should not use a search result with another ticker', async () => {
mockResponses({
search: Response.json({
results: { count: 2, docs: [{ ticker: 'QQQ.US' }] }
})
});
await enhance();
expect(fetchService.fetch).toHaveBeenCalledTimes(1);
});
it('should search again without the suffix of the symbol', async () => {
mockResponses({
search: Response.json({
results: { count: 2, docs: [{ ticker: 'VWCE' }] }
})
});
await enhance({}, 'VWCE.DE');
const urls = fetchService.fetch.mock.calls.map(([url]) => {
return url;
});
expect(urls[0]).toContain('/search_v2/VWCE.DE/');
expect(urls[1]).toContain('/search_v2/VWCE/');
expect(urls[2]).toContain('/data-api/funds/VWCE.json');
});
it.each([ it.each([
['a failed request', new Error('The operation timed out')], ['a failed request', new Error('The operation timed out')],
['an error status', new Response(null, { status: 502 })], ['an error status', new Response(null, { status: 502 })],
@ -193,6 +241,14 @@ describe('TrackinsightDataEnhancerService', () => {
[ [
'top holdings which are not a list', 'top holdings which are not a list',
Response.json({ ...HOLDINGS, topHoldings: 'NVIDIA Corp.' }) Response.json({ ...HOLDINGS, topHoldings: 'NVIDIA Corp.' })
],
[
'countries which are not an object',
Response.json({ ...HOLDINGS, countries: [{ weight: 0.5 }] })
],
[
'sectors which are not an object',
Response.json({ ...HOLDINGS, sectors: [{ weight: 0.5 }] })
] ]
])('should not add lists on %s in the holdings', async (_, holdings) => { ])('should not add lists on %s in the holdings', async (_, holdings) => {
mockResponses({ holdings }); mockResponses({ holdings });
@ -213,7 +269,22 @@ describe('TrackinsightDataEnhancerService', () => {
expect(response.isin).toBe('US46090E1038'); expect(response.isin).toBe('US46090E1038');
}); });
it('should not add empty lists', async () => { it('should not report a failed request as an invalid response', async () => {
const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation();
mockResponses({ holdings: new Response(null, { status: 502 }) });
await enhance();
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('HTTP status 502')
);
warn.mockRestore();
});
it('should set empty lists on a valid response without items', async () => {
mockResponses({ mockResponses({
holdings: Response.json({ holdings: Response.json({
countries: {}, countries: {},
@ -225,9 +296,35 @@ describe('TrackinsightDataEnhancerService', () => {
const response = await enhance(); const response = await enhance();
expect(response).not.toHaveProperty('countries'); expect(response.countries).toEqual([]);
expect(response).not.toHaveProperty('holdings'); expect(response.holdings).toEqual([]);
expect(response).not.toHaveProperty('sectors'); expect(response.sectors).toEqual([]);
});
it('should use the other lists if the top holdings are null', async () => {
mockResponses({
holdings: Response.json({ ...HOLDINGS, topHoldings: null })
});
const response = await enhance();
expect(response.countries).toEqual([{ code: 'US', weight: 0.99 }]);
expect(response.holdings).toEqual([]);
expect(response.sectors).toEqual([
{ name: 'Financial Services', weight: 0.2 },
{ name: 'Technology', weight: 0.8 }
]);
});
it('should use the other lists if the countries are null', async () => {
mockResponses({
holdings: Response.json({ ...HOLDINGS, countries: null })
});
const response = await enhance();
expect(response.countries).toEqual([]);
expect(response.holdings).toEqual([{ name: 'NVIDIA Corp.', weight: 0.08 }]);
}); });
it('should accept floating point noise in a weight', async () => { it('should accept floating point noise in a weight', async () => {

37
apps/api/src/services/data-provider/data-enhancer/trackinsight/trackinsight.service.ts

@ -9,7 +9,8 @@ import { Sector } from '@ghostfolio/common/interfaces/sector.interface';
import { SectorName } from '@ghostfolio/common/types'; import { SectorName } from '@ghostfolio/common/types';
import { Injectable, Logger } from '@nestjs/common'; import { Injectable, Logger } from '@nestjs/common';
import { Prisma, SymbolProfile } from '@prisma/client'; import { SymbolProfile } from '@prisma/client';
import { isPlainObject } from 'lodash-es';
@Injectable() @Injectable()
export class TrackinsightDataEnhancerService implements DataEnhancerInterface { export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
@ -100,6 +101,10 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
url: `${TrackinsightDataEnhancerService.baseUrl}/data-api/holdings/${trackinsightSymbol}.json` url: `${TrackinsightDataEnhancerService.baseUrl}/data-api/holdings/${trackinsightSymbol}.json`
}); });
if (!holdings) {
return response;
}
if (!this.isValidHoldings(holdings)) { if (!this.isValidHoldings(holdings)) {
this.logger.warn( this.logger.warn(
`Could not use the Trackinsight holdings of "${trackinsightSymbol}": Invalid response` `Could not use the Trackinsight holdings of "${trackinsightSymbol}": Invalid response`
@ -119,7 +124,7 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
!response.countries || !response.countries ||
(response.countries as unknown as Country[]).length === 0 (response.countries as unknown as Country[]).length === 0
) { ) {
const countries: Prisma.JsonArray = []; response.countries = [];
for (const [name, value] of Object.entries<any>( for (const [name, value] of Object.entries<any>(
holdings.countries ?? {} holdings.countries ?? {}
@ -131,45 +136,37 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
}); });
if (code) { if (code) {
countries.push({ code, weight: value.weight }); response.countries.push({ code, weight: value.weight });
} }
} }
if (countries.length > 0) {
response.countries = countries;
}
} }
if ( if (
!response.holdings || !response.holdings ||
(response.holdings as unknown as Holding[]).length === 0 (response.holdings as unknown as Holding[]).length === 0
) { ) {
const topHoldings: Prisma.JsonArray = []; response.holdings = [];
for (const { label, weight } of holdings.topHoldings ?? []) { for (const { label, weight } of holdings.topHoldings ?? []) {
if (label.toLowerCase() === 'other') { if (label.toLowerCase() === 'other') {
continue; continue;
} }
topHoldings.push({ response.holdings.push({
weight, weight,
name: label name: label
}); });
} }
if (topHoldings.length > 0) {
response.holdings = topHoldings;
}
} }
if ( if (
!response.sectors || !response.sectors ||
(response.sectors as unknown as Sector[]).length === 0 (response.sectors as unknown as Sector[]).length === 0
) { ) {
const sectors: Prisma.JsonArray = []; response.sectors = [];
for (const [name, value] of Object.entries<any>(holdings.sectors ?? {})) { for (const [name, value] of Object.entries<any>(holdings.sectors ?? {})) {
sectors.push({ response.sectors.push({
name: getSectorName({ name: getSectorName({
name, name,
aliases: TrackinsightDataEnhancerService.sectorsMapping aliases: TrackinsightDataEnhancerService.sectorsMapping
@ -177,10 +174,6 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
weight: value.weight weight: value.weight
}); });
} }
if (sectors.length > 0) {
response.sectors = sectors;
}
} }
return Promise.resolve(response); return Promise.resolve(response);
@ -226,7 +219,11 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
const { countries, sectors, topHoldings } = holdings; const { countries, sectors, topHoldings } = holdings;
if (topHoldings !== undefined && !Array.isArray(topHoldings)) { if (
!isPlainObject(countries ?? {}) ||
!isPlainObject(sectors ?? {}) ||
!Array.isArray(topHoldings ?? [])
) {
return false; return false;
} }

Loading…
Cancel
Save