Simplify initial project setup (#12)
* Simplify initial project setup * Added a validation for environment variables * Added support for feature flags to simplify the initial project setup * Add configuration service to test * Optimize data gathering and exchange rate calculation (#14) * Clean up changelog
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { DataGatheringService } from '../../services/data-gathering.service';
|
||||
import { DataProviderService } from '../../services/data-provider.service';
|
||||
import { AlphaVantageService } from '../../services/data-provider/alpha-vantage/alpha-vantage.service';
|
||||
@@ -16,6 +17,7 @@ import { AdminService } from './admin.service';
|
||||
providers: [
|
||||
AdminService,
|
||||
AlphaVantageService,
|
||||
ConfigurationService,
|
||||
DataGatheringService,
|
||||
DataProviderService,
|
||||
ExchangeRateDataService,
|
||||
|
@@ -5,6 +5,7 @@ import { ConfigModule } from '@nestjs/config';
|
||||
import { ScheduleModule } from '@nestjs/schedule';
|
||||
import { ServeStaticModule } from '@nestjs/serve-static';
|
||||
|
||||
import { ConfigurationService } from '../services/configuration.service';
|
||||
import { CronService } from '../services/cron.service';
|
||||
import { DataGatheringService } from '../services/data-gathering.service';
|
||||
import { DataProviderService } from '../services/data-provider.service';
|
||||
@@ -59,6 +60,7 @@ import { UserModule } from './user/user.module';
|
||||
controllers: [AppController],
|
||||
providers: [
|
||||
AlphaVantageService,
|
||||
ConfigurationService,
|
||||
CronService,
|
||||
DataGatheringService,
|
||||
DataProviderService,
|
||||
|
@@ -10,11 +10,15 @@ import {
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
public constructor(private readonly authService: AuthService) {}
|
||||
public constructor(
|
||||
private readonly authService: AuthService,
|
||||
private readonly configurationService: ConfigurationService
|
||||
) {}
|
||||
|
||||
@Get('anonymous/:accessToken')
|
||||
public async accessTokenLogin(@Param('accessToken') accessToken: string) {
|
||||
@@ -44,9 +48,9 @@ export class AuthController {
|
||||
const jwt: string = req.user.jwt;
|
||||
|
||||
if (jwt) {
|
||||
res.redirect(`${process.env.ROOT_URL}/auth/${jwt}`);
|
||||
res.redirect(`${this.configurationService.get('ROOT_URL')}/auth/${jwt}`);
|
||||
} else {
|
||||
res.redirect(`${process.env.ROOT_URL}/auth`);
|
||||
res.redirect(`${this.configurationService.get('ROOT_URL')}/auth`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { PrismaService } from '../../services/prisma.service';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
@@ -18,6 +19,7 @@ import { JwtStrategy } from './jwt.strategy';
|
||||
],
|
||||
providers: [
|
||||
AuthService,
|
||||
ConfigurationService,
|
||||
GoogleStrategy,
|
||||
JwtStrategy,
|
||||
PrismaService,
|
||||
|
@@ -1,13 +1,15 @@
|
||||
import { Injectable, InternalServerErrorException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { ValidateOAuthLoginParams } from './interfaces/interfaces';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
public constructor(
|
||||
private jwtService: JwtService,
|
||||
private readonly configurationService: ConfigurationService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly userService: UserService
|
||||
) {}
|
||||
|
||||
@@ -16,7 +18,7 @@ export class AuthService {
|
||||
try {
|
||||
const hashedAccessToken = this.userService.createAccessToken(
|
||||
accessToken,
|
||||
process.env.ACCESS_TOKEN_SALT
|
||||
this.configurationService.get('ACCESS_TOKEN_SALT')
|
||||
);
|
||||
|
||||
const [user] = await this.userService.users({
|
||||
|
@@ -3,15 +3,21 @@ import { PassportStrategy } from '@nestjs/passport';
|
||||
import { Provider } from '@prisma/client';
|
||||
import { Strategy } from 'passport-google-oauth20';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
@Injectable()
|
||||
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
|
||||
public constructor(private readonly authService: AuthService) {
|
||||
public constructor(
|
||||
private readonly authService: AuthService,
|
||||
readonly configurationService: ConfigurationService
|
||||
) {
|
||||
super({
|
||||
callbackURL: `${process.env.ROOT_URL}/api/auth/google/callback`,
|
||||
clientID: process.env.GOOGLE_CLIENT_ID,
|
||||
clientSecret: process.env.GOOGLE_SECRET,
|
||||
callbackURL: `${configurationService.get(
|
||||
'ROOT_URL'
|
||||
)}/api/auth/google/callback`,
|
||||
clientID: configurationService.get('GOOGLE_CLIENT_ID'),
|
||||
clientSecret: configurationService.get('GOOGLE_SECRET'),
|
||||
passReqToCallback: true,
|
||||
scope: ['email', 'profile']
|
||||
});
|
||||
|
@@ -2,18 +2,20 @@ import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { PrismaService } from '../../services/prisma.service';
|
||||
import { UserService } from '../user/user.service';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
public constructor(
|
||||
readonly configurationService: ConfigurationService,
|
||||
private prisma: PrismaService,
|
||||
private readonly userService: UserService
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: process.env.JWT_SECRET_KEY
|
||||
secretOrKey: configurationService.get('JWT_SECRET_KEY')
|
||||
});
|
||||
}
|
||||
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { DataProviderService } from '../../services/data-provider.service';
|
||||
import { AlphaVantageService } from '../../services/data-provider/alpha-vantage/alpha-vantage.service';
|
||||
import { RakutenRapidApiService } from '../../services/data-provider/rakuten-rapid-api/rakuten-rapid-api.service';
|
||||
@@ -15,6 +16,7 @@ import { ExperimentalService } from './experimental.service';
|
||||
controllers: [ExperimentalController],
|
||||
providers: [
|
||||
AlphaVantageService,
|
||||
ConfigurationService,
|
||||
DataProviderService,
|
||||
ExchangeRateDataService,
|
||||
ExperimentalService,
|
||||
|
@@ -1,6 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { PrismaService } from '../../services/prisma.service';
|
||||
import { InfoController } from './info.controller';
|
||||
import { InfoService } from './info.service';
|
||||
@@ -13,6 +14,6 @@ import { InfoService } from './info.service';
|
||||
})
|
||||
],
|
||||
controllers: [InfoController],
|
||||
providers: [InfoService, PrismaService]
|
||||
providers: [ConfigurationService, InfoService, PrismaService]
|
||||
})
|
||||
export class InfoModule {}
|
||||
|
@@ -1,7 +1,9 @@
|
||||
import { permissions } from '@ghostfolio/helper';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Currency } from '@prisma/client';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { PrismaService } from '../../services/prisma.service';
|
||||
import { InfoItem } from './interfaces/info-item.interface';
|
||||
|
||||
@@ -10,6 +12,7 @@ export class InfoService {
|
||||
private static DEMO_USER_ID = '9b112b4d-3b7d-4bad-9bdd-3b0f7b4dac2f';
|
||||
|
||||
public constructor(
|
||||
private readonly configurationService: ConfigurationService,
|
||||
private jwtService: JwtService,
|
||||
private prisma: PrismaService
|
||||
) {}
|
||||
@@ -20,7 +23,14 @@ export class InfoService {
|
||||
select: { id: true, name: true }
|
||||
});
|
||||
|
||||
const globalPermissions: string[] = [];
|
||||
|
||||
if (this.configurationService.get('ENABLE_FEATURE_SOCIAL_LOGIN')) {
|
||||
globalPermissions.push(permissions.useSocialLogin);
|
||||
}
|
||||
|
||||
return {
|
||||
globalPermissions,
|
||||
platforms,
|
||||
currencies: Object.values(Currency),
|
||||
demoAuthToken: this.getDemoAuthToken(),
|
||||
|
@@ -3,6 +3,7 @@ import { Currency } from '@prisma/client';
|
||||
export interface InfoItem {
|
||||
currencies: Currency[];
|
||||
demoAuthToken: string;
|
||||
globalPermissions: string[];
|
||||
lastDataGathering?: Date;
|
||||
message?: {
|
||||
text: string;
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { DataGatheringService } from '../../services/data-gathering.service';
|
||||
import { DataProviderService } from '../../services/data-provider.service';
|
||||
import { AlphaVantageService } from '../../services/data-provider/alpha-vantage/alpha-vantage.service';
|
||||
@@ -18,6 +19,7 @@ import { OrderService } from './order.service';
|
||||
providers: [
|
||||
AlphaVantageService,
|
||||
CacheService,
|
||||
ConfigurationService,
|
||||
DataGatheringService,
|
||||
DataProviderService,
|
||||
ImpersonationService,
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { DataGatheringService } from '../../services/data-gathering.service';
|
||||
import { DataProviderService } from '../../services/data-provider.service';
|
||||
import { AlphaVantageService } from '../../services/data-provider/alpha-vantage/alpha-vantage.service';
|
||||
@@ -22,6 +23,7 @@ import { PortfolioService } from './portfolio.service';
|
||||
providers: [
|
||||
AlphaVantageService,
|
||||
CacheService,
|
||||
ConfigurationService,
|
||||
DataGatheringService,
|
||||
DataProviderService,
|
||||
ExchangeRateDataService,
|
||||
|
@@ -2,6 +2,7 @@ import { CacheModule, Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import * as redisStore from 'cache-manager-redis-store';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { RedisCacheService } from './redis-cache.service';
|
||||
|
||||
@Module({
|
||||
@@ -9,16 +10,16 @@ import { RedisCacheService } from './redis-cache.service';
|
||||
CacheModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: async (configService: ConfigService) => ({
|
||||
host: configService.get('REDIS_HOST'),
|
||||
max: configService.get('MAX_ITEM_IN_CACHE'),
|
||||
port: configService.get('REDIS_PORT'),
|
||||
useFactory: async (configurationService: ConfigurationService) => ({
|
||||
host: configurationService.get('REDIS_HOST'),
|
||||
max: configurationService.get('MAX_ITEM_IN_CACHE'),
|
||||
port: configurationService.get('REDIS_PORT'),
|
||||
store: redisStore,
|
||||
ttl: configService.get('CACHE_TTL')
|
||||
ttl: configurationService.get('CACHE_TTL')
|
||||
})
|
||||
})
|
||||
],
|
||||
providers: [RedisCacheService],
|
||||
providers: [ConfigurationService, RedisCacheService],
|
||||
exports: [RedisCacheService]
|
||||
})
|
||||
export class RedisCacheModule {}
|
||||
|
@@ -1,9 +1,14 @@
|
||||
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
|
||||
import { Cache } from 'cache-manager';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
|
||||
@Injectable()
|
||||
export class RedisCacheService {
|
||||
public constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {}
|
||||
public constructor(
|
||||
@Inject(CACHE_MANAGER) private readonly cache: Cache,
|
||||
private readonly configurationService: ConfigurationService
|
||||
) {}
|
||||
|
||||
public async get(key: string): Promise<string> {
|
||||
return await this.cache.get(key);
|
||||
@@ -18,6 +23,8 @@ export class RedisCacheService {
|
||||
}
|
||||
|
||||
public async set(key: string, value: string) {
|
||||
await this.cache.set(key, value, { ttl: Number(process.env.CACHE_TTL) });
|
||||
await this.cache.set(key, value, {
|
||||
ttl: this.configurationService.get('CACHE_TTL')
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { DataProviderService } from '../../services/data-provider.service';
|
||||
import { AlphaVantageService } from '../../services/data-provider/alpha-vantage/alpha-vantage.service';
|
||||
import { RakutenRapidApiService } from '../../services/data-provider/rakuten-rapid-api/rakuten-rapid-api.service';
|
||||
@@ -13,6 +14,7 @@ import { SymbolService } from './symbol.service';
|
||||
controllers: [SymbolController],
|
||||
providers: [
|
||||
AlphaVantageService,
|
||||
ConfigurationService,
|
||||
DataProviderService,
|
||||
PrismaService,
|
||||
RakutenRapidApiService,
|
||||
|
@@ -1,6 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { PrismaService } from '../../services/prisma.service';
|
||||
import { UserController } from './user.controller';
|
||||
import { UserService } from './user.service';
|
||||
@@ -13,6 +14,6 @@ import { UserService } from './user.service';
|
||||
})
|
||||
],
|
||||
controllers: [UserController],
|
||||
providers: [PrismaService, UserService]
|
||||
providers: [ConfigurationService, PrismaService, UserService]
|
||||
})
|
||||
export class UserModule {}
|
||||
|
@@ -1,9 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Currency, Prisma, Provider, User } from '@prisma/client';
|
||||
import { add } from 'date-fns';
|
||||
import { locale, resetHours } from 'libs/helper/src';
|
||||
import { locale, permissions, resetHours } from 'libs/helper/src';
|
||||
import { getPermissions } from 'libs/helper/src';
|
||||
|
||||
import { ConfigurationService } from '../../services/configuration.service';
|
||||
import { PrismaService } from '../../services/prisma.service';
|
||||
import { UserWithSettings } from '../interfaces/user-with-settings';
|
||||
import { User as IUser } from './interfaces/user.interface';
|
||||
@@ -14,7 +15,10 @@ const crypto = require('crypto');
|
||||
export class UserService {
|
||||
public static DEFAULT_CURRENCY = Currency.USD;
|
||||
|
||||
public constructor(private prisma: PrismaService) {}
|
||||
public constructor(
|
||||
private readonly configurationService: ConfigurationService,
|
||||
private prisma: PrismaService
|
||||
) {}
|
||||
|
||||
public async getUser({
|
||||
alias,
|
||||
@@ -30,6 +34,16 @@ export class UserService {
|
||||
where: { GranteeUser: { id } }
|
||||
});
|
||||
|
||||
const currentPermissions = getPermissions(role);
|
||||
|
||||
if (this.configurationService.get('ENABLE_FEATURE_FEAR_AND_GREED_INDEX')) {
|
||||
currentPermissions.push(permissions.accessFearAndGreedIndex);
|
||||
}
|
||||
|
||||
if (this.configurationService.get('ENABLE_FEATURE_SOCIAL_LOGIN')) {
|
||||
currentPermissions.push(permissions.useSocialLogin);
|
||||
}
|
||||
|
||||
return {
|
||||
alias,
|
||||
id,
|
||||
@@ -39,7 +53,7 @@ export class UserService {
|
||||
id: accessItem.id
|
||||
};
|
||||
}),
|
||||
permissions: getPermissions(role),
|
||||
permissions: currentPermissions,
|
||||
settings: {
|
||||
baseCurrency: Settings?.currency || UserService.DEFAULT_CURRENCY,
|
||||
locale
|
||||
|
@@ -4,6 +4,7 @@ import { baseCurrency } from 'libs/helper/src';
|
||||
import { getYesterday } from 'libs/helper/src';
|
||||
import { getUtc } from 'libs/helper/src';
|
||||
|
||||
import { ConfigurationService } from '../services/configuration.service';
|
||||
import { DataProviderService } from '../services/data-provider.service';
|
||||
import { AlphaVantageService } from '../services/data-provider/alpha-vantage/alpha-vantage.service';
|
||||
import { RakutenRapidApiService } from '../services/data-provider/rakuten-rapid-api/rakuten-rapid-api.service';
|
||||
@@ -15,6 +16,7 @@ import { Portfolio } from './portfolio';
|
||||
|
||||
describe('Portfolio', () => {
|
||||
let alphaVantageService: AlphaVantageService;
|
||||
let configurationService: ConfigurationService;
|
||||
let dataProviderService: DataProviderService;
|
||||
let exchangeRateDataService: ExchangeRateDataService;
|
||||
let portfolio: Portfolio;
|
||||
@@ -28,6 +30,7 @@ describe('Portfolio', () => {
|
||||
imports: [],
|
||||
providers: [
|
||||
AlphaVantageService,
|
||||
ConfigurationService,
|
||||
DataProviderService,
|
||||
ExchangeRateDataService,
|
||||
PrismaService,
|
||||
@@ -38,6 +41,7 @@ describe('Portfolio', () => {
|
||||
}).compile();
|
||||
|
||||
alphaVantageService = app.get<AlphaVantageService>(AlphaVantageService);
|
||||
configurationService = app.get<ConfigurationService>(ConfigurationService);
|
||||
dataProviderService = app.get<DataProviderService>(DataProviderService);
|
||||
exchangeRateDataService = app.get<ExchangeRateDataService>(
|
||||
ExchangeRateDataService
|
||||
|
32
apps/api/src/services/configuration.service.ts
Normal file
32
apps/api/src/services/configuration.service.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { bool, cleanEnv, num, port, str } from 'envalid';
|
||||
|
||||
import { Environment } from './interfaces/environment.interface';
|
||||
|
||||
@Injectable()
|
||||
export class ConfigurationService {
|
||||
private readonly environmentConfiguration: Environment;
|
||||
|
||||
public constructor() {
|
||||
this.environmentConfiguration = cleanEnv(process.env, {
|
||||
ACCESS_TOKEN_SALT: str(),
|
||||
ALPHA_VANTAGE_API_KEY: str({ default: '' }),
|
||||
CACHE_TTL: num({ default: 1 }),
|
||||
ENABLE_FEATURE_FEAR_AND_GREED_INDEX: bool({ default: false }),
|
||||
ENABLE_FEATURE_SOCIAL_LOGIN: bool({ default: false }),
|
||||
GOOGLE_CLIENT_ID: str({ default: 'dummyClientId' }),
|
||||
GOOGLE_SECRET: str({ default: 'dummySecret' }),
|
||||
JWT_SECRET_KEY: str({}),
|
||||
MAX_ITEM_IN_CACHE: num({ default: 9999 }),
|
||||
PORT: port({ default: 3333 }),
|
||||
RAKUTEN_RAPID_API_KEY: str({ default: '' }),
|
||||
REDIS_HOST: str({ default: 'localhost' }),
|
||||
REDIS_PORT: port({ default: 6379 }),
|
||||
ROOT_URL: str({ default: 'http://localhost:4200' })
|
||||
});
|
||||
}
|
||||
|
||||
public get<K extends keyof Environment>(key: K): Environment[K] {
|
||||
return this.environmentConfiguration[key];
|
||||
}
|
||||
}
|
@@ -11,13 +11,15 @@ import {
|
||||
import { benchmarks, currencyPairs } from 'libs/helper/src';
|
||||
import { getUtc, resetHours } from 'libs/helper/src';
|
||||
|
||||
import { ConfigurationService } from './configuration.service';
|
||||
import { DataProviderService } from './data-provider.service';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class DataGatheringService {
|
||||
public constructor(
|
||||
private dataProviderService: DataProviderService,
|
||||
private readonly configurationService: ConfigurationService,
|
||||
private readonly dataProviderService: DataProviderService,
|
||||
private prisma: PrismaService
|
||||
) {}
|
||||
|
||||
@@ -64,9 +66,11 @@ export class DataGatheringService {
|
||||
}
|
||||
|
||||
public async gatherMax() {
|
||||
const isDataGatheringNeeded = await this.isDataGatheringNeeded();
|
||||
const isDataGatheringLocked = await this.prisma.property.findUnique({
|
||||
where: { key: 'LOCKED_DATA_GATHERING' }
|
||||
});
|
||||
|
||||
if (isDataGatheringNeeded) {
|
||||
if (!isDataGatheringLocked) {
|
||||
console.log('Max data gathering has been started.');
|
||||
console.time('data-gathering');
|
||||
|
||||
@@ -174,6 +178,24 @@ export class DataGatheringService {
|
||||
}
|
||||
}
|
||||
|
||||
private getBenchmarksToGather(startDate: Date) {
|
||||
const benchmarksToGather = benchmarks.map((symbol) => {
|
||||
return {
|
||||
symbol,
|
||||
date: startDate
|
||||
};
|
||||
});
|
||||
|
||||
if (this.configurationService.get('ENABLE_FEATURE_FEAR_AND_GREED_INDEX')) {
|
||||
benchmarksToGather.push({
|
||||
date: startDate,
|
||||
symbol: 'GF.FEAR_AND_GREED_INDEX'
|
||||
});
|
||||
}
|
||||
|
||||
return benchmarksToGather;
|
||||
}
|
||||
|
||||
private async getSymbols7D(): Promise<{ date: Date; symbol: string }[]> {
|
||||
const startDate = subDays(resetHours(new Date()), 7);
|
||||
|
||||
@@ -190,13 +212,6 @@ export class DataGatheringService {
|
||||
};
|
||||
});
|
||||
|
||||
const benchmarksToGather = benchmarks.map((symbol) => {
|
||||
return {
|
||||
symbol,
|
||||
date: startDate
|
||||
};
|
||||
});
|
||||
|
||||
const currencyPairsToGather = currencyPairs.map((symbol) => {
|
||||
return {
|
||||
symbol,
|
||||
@@ -205,7 +220,7 @@ export class DataGatheringService {
|
||||
});
|
||||
|
||||
return [
|
||||
...benchmarksToGather,
|
||||
...this.getBenchmarksToGather(startDate),
|
||||
...currencyPairsToGather,
|
||||
...distinctOrdersWithDate
|
||||
];
|
||||
@@ -220,13 +235,6 @@ export class DataGatheringService {
|
||||
select: { date: true, symbol: true }
|
||||
});
|
||||
|
||||
const benchmarksToGather = benchmarks.map((symbol) => {
|
||||
return {
|
||||
symbol,
|
||||
date: startDate
|
||||
};
|
||||
});
|
||||
|
||||
const currencyPairsToGather = currencyPairs.map((symbol) => {
|
||||
return {
|
||||
symbol,
|
||||
@@ -234,7 +242,11 @@ export class DataGatheringService {
|
||||
};
|
||||
});
|
||||
|
||||
return [...benchmarksToGather, ...currencyPairsToGather, ...distinctOrders];
|
||||
return [
|
||||
...this.getBenchmarksToGather(startDate),
|
||||
...currencyPairsToGather,
|
||||
...distinctOrders
|
||||
];
|
||||
}
|
||||
|
||||
private async isDataGatheringNeeded() {
|
||||
|
@@ -1,6 +1,7 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { isAfter, isBefore, parse } from 'date-fns';
|
||||
|
||||
import { ConfigurationService } from '../../configuration.service';
|
||||
import { DataProviderInterface } from '../../interfaces/data-provider.interface';
|
||||
import { Granularity } from '../../interfaces/granularity.type';
|
||||
import {
|
||||
@@ -9,13 +10,17 @@ import {
|
||||
} from '../../interfaces/interfaces';
|
||||
import { IAlphaVantageHistoricalResponse } from './interfaces/interfaces';
|
||||
|
||||
const alphaVantage = require('alphavantage')({
|
||||
key: process.env.ALPHA_VANTAGE_API_KEY
|
||||
});
|
||||
|
||||
@Injectable()
|
||||
export class AlphaVantageService implements DataProviderInterface {
|
||||
public constructor() {}
|
||||
public alphaVantage;
|
||||
|
||||
public constructor(
|
||||
private readonly configurationService: ConfigurationService
|
||||
) {
|
||||
this.alphaVantage = require('alphavantage')({
|
||||
key: this.configurationService.get('ALPHA_VANTAGE_API_KEY')
|
||||
});
|
||||
}
|
||||
|
||||
public async get(
|
||||
aSymbols: string[]
|
||||
@@ -40,7 +45,7 @@ export class AlphaVantageService implements DataProviderInterface {
|
||||
try {
|
||||
const historicalData: {
|
||||
[symbol: string]: IAlphaVantageHistoricalResponse[];
|
||||
} = await alphaVantage.crypto.daily(
|
||||
} = await this.alphaVantage.crypto.daily(
|
||||
symbol.substring(0, symbol.length - 3).toLowerCase(),
|
||||
'usd'
|
||||
);
|
||||
@@ -73,6 +78,6 @@ export class AlphaVantageService implements DataProviderInterface {
|
||||
}
|
||||
|
||||
public search(aSymbol: string) {
|
||||
return alphaVantage.data.search(aSymbol);
|
||||
return this.alphaVantage.data.search(aSymbol);
|
||||
}
|
||||
}
|
||||
|
@@ -3,6 +3,7 @@ import * as bent from 'bent';
|
||||
import { format, subMonths, subWeeks, subYears } from 'date-fns';
|
||||
import { getToday, getYesterday } from 'libs/helper/src';
|
||||
|
||||
import { ConfigurationService } from '../../configuration.service';
|
||||
import { DataProviderInterface } from '../../interfaces/data-provider.interface';
|
||||
import { Granularity } from '../../interfaces/granularity.type';
|
||||
import {
|
||||
@@ -17,7 +18,9 @@ export class RakutenRapidApiService implements DataProviderInterface {
|
||||
|
||||
private prisma: PrismaService;
|
||||
|
||||
public constructor() {}
|
||||
public constructor(
|
||||
private readonly configurationService: ConfigurationService
|
||||
) {}
|
||||
|
||||
public async get(
|
||||
aSymbols: string[]
|
||||
@@ -127,7 +130,9 @@ export class RakutenRapidApiService implements DataProviderInterface {
|
||||
{
|
||||
useQueryString: true,
|
||||
'x-rapidapi-host': 'fear-and-greed-index.p.rapidapi.com',
|
||||
'x-rapidapi-key': process.env.RAKUTEN_RAPID_API_KEY
|
||||
'x-rapidapi-key': this.configurationService.get(
|
||||
'RAKUTEN_RAPID_API_KEY'
|
||||
)
|
||||
}
|
||||
);
|
||||
|
||||
|
@@ -1,7 +1,7 @@
|
||||
import { getYesterday } from '@ghostfolio/helper';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Currency } from '@prisma/client';
|
||||
import { format } from 'date-fns';
|
||||
import { getYesterday } from 'libs/helper/src';
|
||||
|
||||
import { DataProviderService } from './data-provider.service';
|
||||
|
||||
@@ -15,6 +15,8 @@ export class ExchangeRateDataService {
|
||||
}
|
||||
|
||||
public async initialize() {
|
||||
this.pairs = [];
|
||||
|
||||
this.addPairs(Currency.CHF, Currency.EUR);
|
||||
this.addPairs(Currency.CHF, Currency.GBP);
|
||||
this.addPairs(Currency.CHF, Currency.USD);
|
||||
@@ -25,11 +27,6 @@ export class ExchangeRateDataService {
|
||||
await this.loadCurrencies();
|
||||
}
|
||||
|
||||
private addPairs(aCurrency1: Currency, aCurrency2: Currency) {
|
||||
this.pairs.push(`${aCurrency1}${aCurrency2}`);
|
||||
this.pairs.push(`${aCurrency2}${aCurrency1}`);
|
||||
}
|
||||
|
||||
public async loadCurrencies() {
|
||||
const result = await this.dataProviderService.getHistorical(
|
||||
this.pairs,
|
||||
@@ -38,19 +35,34 @@ export class ExchangeRateDataService {
|
||||
getYesterday()
|
||||
);
|
||||
|
||||
const resultExtended = result;
|
||||
|
||||
Object.keys(result).forEach((pair) => {
|
||||
const [currency1, currency2] = pair.match(/.{1,3}/g);
|
||||
const [date] = Object.keys(result[pair]);
|
||||
|
||||
// Calculate the opposite direction
|
||||
resultExtended[`${currency2}${currency1}`] = {
|
||||
[date]: {
|
||||
marketPrice: 1 / result[pair][date].marketPrice
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
this.pairs.forEach((pair) => {
|
||||
this.currencies[pair] =
|
||||
result[pair]?.[format(getYesterday(), 'yyyy-MM-dd')]?.marketPrice || 1;
|
||||
const [currency1, currency2] = pair.match(/.{1,3}/g);
|
||||
const date = format(getYesterday(), 'yyyy-MM-dd');
|
||||
|
||||
if (this.currencies[pair] === 1) {
|
||||
// Calculate the other direction
|
||||
const [currency1, currency2] = pair.match(/.{1,3}/g);
|
||||
this.currencies[pair] = resultExtended[pair]?.[date]?.marketPrice;
|
||||
|
||||
if (!this.currencies[pair]) {
|
||||
// Not found, calculate indirectly via USD
|
||||
this.currencies[pair] =
|
||||
1 /
|
||||
result[`${currency2}${currency1}`]?.[
|
||||
format(getYesterday(), 'yyyy-MM-dd')
|
||||
]?.marketPrice;
|
||||
resultExtended[`${currency1}${Currency.USD}`][date].marketPrice *
|
||||
resultExtended[`${Currency.USD}${currency2}`][date].marketPrice;
|
||||
|
||||
// Calculate the opposite direction
|
||||
this.currencies[`${currency2}${currency1}`] = 1 / this.currencies[pair];
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -60,6 +72,11 @@ export class ExchangeRateDataService {
|
||||
aFromCurrency: Currency,
|
||||
aToCurrency: Currency
|
||||
) {
|
||||
if (isNaN(this.currencies[`${Currency.USD}${Currency.CHF}`])) {
|
||||
// Reinitialize if data is not loaded correctly
|
||||
this.initialize();
|
||||
}
|
||||
|
||||
let factor = 1;
|
||||
|
||||
if (aFromCurrency !== aToCurrency) {
|
||||
@@ -68,4 +85,9 @@ export class ExchangeRateDataService {
|
||||
|
||||
return factor * aValue;
|
||||
}
|
||||
|
||||
private addPairs(aCurrency1: Currency, aCurrency2: Currency) {
|
||||
this.pairs.push(`${aCurrency1}${aCurrency2}`);
|
||||
this.pairs.push(`${aCurrency2}${aCurrency1}`);
|
||||
}
|
||||
}
|
||||
|
18
apps/api/src/services/interfaces/environment.interface.ts
Normal file
18
apps/api/src/services/interfaces/environment.interface.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { CleanedEnvAccessors } from 'envalid';
|
||||
|
||||
export interface Environment extends CleanedEnvAccessors {
|
||||
ACCESS_TOKEN_SALT: string;
|
||||
ALPHA_VANTAGE_API_KEY: string;
|
||||
CACHE_TTL: number;
|
||||
ENABLE_FEATURE_FEAR_AND_GREED_INDEX: boolean;
|
||||
ENABLE_FEATURE_SOCIAL_LOGIN: boolean;
|
||||
GOOGLE_CLIENT_ID: string;
|
||||
GOOGLE_SECRET: string;
|
||||
JWT_SECRET_KEY: string;
|
||||
MAX_ITEM_IN_CACHE: number;
|
||||
PORT: number;
|
||||
RAKUTEN_RAPID_API_KEY: string;
|
||||
REDIS_HOST: string;
|
||||
REDIS_PORT: number;
|
||||
ROOT_URL: string;
|
||||
}
|
Reference in New Issue
Block a user