ghostfolio/apps/api/src/app/core/current-rate.service.ts

104 lines
2.5 KiB
TypeScript
Raw Normal View History

2021-07-08 22:42:19 +02:00
import { DataProviderService } from '@ghostfolio/api/services/data-provider.service';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data.service';
import { resetHours } from '@ghostfolio/common/helper';
2021-07-03 16:37:33 +02:00
import { Injectable } from '@nestjs/common';
import { Currency } from '@prisma/client';
2021-07-08 22:42:19 +02:00
import { isToday } from 'date-fns';
2021-07-03 16:37:33 +02:00
import { MarketDataService } from './market-data.service';
2021-07-03 16:37:33 +02:00
@Injectable()
export class CurrentRateService {
public constructor(
2021-07-08 22:42:19 +02:00
private readonly dataProviderService: DataProviderService,
private readonly exchangeRateDataService: ExchangeRateDataService,
2021-07-03 16:37:33 +02:00
private readonly marketDataService: MarketDataService
) {}
2021-07-03 16:37:33 +02:00
public async getValue({
currency,
date,
symbol,
userCurrency
}: GetValueParams): Promise<GetValueObject> {
2021-07-08 22:42:19 +02:00
if (isToday(date)) {
const dataProviderResult = await this.dataProviderService.get([symbol]);
return {
date: resetHours(date),
marketPrice: dataProviderResult?.[symbol]?.marketPrice ?? 0
};
2021-07-08 22:42:19 +02:00
}
2021-07-03 16:37:33 +02:00
const marketData = await this.marketDataService.get({
date,
symbol
});
2021-07-03 16:37:33 +02:00
if (marketData) {
return {
date: marketData.date,
marketPrice: this.exchangeRateDataService.toCurrency(
marketData.marketPrice,
currency,
userCurrency
)
};
2021-07-03 16:37:33 +02:00
}
throw new Error(`Value not found for ${symbol} at ${resetHours(date)}`);
}
public async getValues({
currency,
dateRangeEnd,
dateRangeStart,
symbol,
userCurrency
}: GetValuesParams): Promise<GetValueObject[]> {
const marketData = await this.marketDataService.getRange({
dateRangeEnd,
dateRangeStart,
symbol
});
if (marketData) {
return marketData.map((marketDataItem) => {
return {
date: marketDataItem.date,
marketPrice: this.exchangeRateDataService.toCurrency(
marketDataItem.marketPrice,
currency,
userCurrency
)
};
});
}
throw new Error(
`Values not found for ${symbol} from ${resetHours(
dateRangeStart
)} to ${resetHours(dateRangeEnd)}`
);
}
}
export interface GetValueParams {
date: Date;
symbol: string;
currency: Currency;
userCurrency: Currency;
}
export interface GetValuesParams {
dateRangeEnd: Date;
dateRangeStart: Date;
symbol: string;
currency: Currency;
userCurrency: Currency;
}
export interface GetValueObject {
date: Date;
marketPrice: number;
}