Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#12] 4.04 오늘의 상/하위 종목 API 구현 #30

Merged
merged 8 commits into from
Nov 7, 2024
Next Next commit
✨ feat: access_token을 발급받는 로직 구현#12
오늘의 상/하위 종목 조회를 위해 필요한 access_token 발급 로직 구현
uuuo3o committed Nov 6, 2024
commit a86bf218e52a17c1cfe2973e64d81ab32dfd9448
43 changes: 43 additions & 0 deletions BE/src/stocks/topfive/topfive.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import axios from 'axios';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class TopFiveService {
private accessToken: string;
private tokenExpireTime: Date;
private readonly koreaInvestmentConfig: {
appKey: string;
appSecret: string;
baseUrl: string;
};

constructor(private readonly config: ConfigService) {
this.koreaInvestmentConfig = {
appKey: this.config.get<string>('KOREA_INVESTMENT_APP_KEY'),
appSecret: this.config.get<string>('KOREA_INVESTMENT_APP_SECRET'),
baseUrl: this.config.get<string>('KOREA_INVESTMENT_BASE_URL'),
};
}

private async getAccessToken() {
// accessToken이 유효한 경우
if (this.accessToken && this.tokenExpireTime > new Date()) {
return this.accessToken;
}

const response = await axios.post(
`${this.koreaInvestmentConfig.baseUrl}/oauth2/tokenP`,
{
grant_type: 'client_credentials',
appkey: this.koreaInvestmentConfig.appKey,
appsecret: this.koreaInvestmentConfig.appSecret,
},
);

this.accessToken = response.data.access_token;
this.tokenExpireTime = new Date(Date.now() + +response.data.expires_in);

return this.accessToken;
}
}