Skip to content

Commit 58ed3b8

Browse files
authored
Merge pull request #7 from yepcode/feature/YEP-2896
YEP-2896 Refresh access token on YepCode Run SDK
2 parents 4df9ddb + a1e6ffd commit 58ed3b8

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

src/api/yepcodeApi.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,12 @@ export class YepCodeApi {
164164
}
165165

166166
private async getAccessToken(): Promise<string> {
167+
if (!this.clientId || !this.clientSecret) {
168+
throw new Error(
169+
"AccessToken has expired. Provide a new one or enable automatic refreshing by providing an apiToken or clientId and clientSecret."
170+
);
171+
}
172+
167173
try {
168174
const response = await fetch(this.authUrl, {
169175
method: "POST",
@@ -190,6 +196,19 @@ export class YepCodeApi {
190196
}
191197
}
192198

199+
private isAccessTokenExpired(accessToken: string): boolean {
200+
const tokenPayload = accessToken.split(".")[1];
201+
if (!tokenPayload) {
202+
return true;
203+
}
204+
205+
const decodedPayload = JSON.parse(
206+
Buffer.from(tokenPayload, "base64").toString()
207+
);
208+
209+
return decodedPayload.exp < Date.now() / 1000;
210+
}
211+
193212
private sanitizeDateParam(date?: Date | string): string | undefined {
194213
if (!date) {
195214
return undefined;
@@ -213,7 +232,7 @@ export class YepCodeApi {
213232
endpoint: string,
214233
options: RequestOptions = {}
215234
): Promise<T> {
216-
if (!this.accessToken) {
235+
if (!this.accessToken || this.isAccessTokenExpired(this.accessToken)) {
217236
await this.getAccessToken();
218237
}
219238

0 commit comments

Comments
 (0)