Skip to content

Commit 5f3478b

Browse files
committed
feat: cache accessToken
1 parent bea84c0 commit 5f3478b

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/apis/AuthAPI.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,17 @@ import { fmAxios } from '../helpers/fmAxios';
33
import { FMAuthMethod } from '../types/FMAxios';
44
import { AuthResponse, EmptyResponse, FilemakerDataAPI } from '..';
55

6+
const TIME_LIMIT = 1000 * 60 * 15;
7+
68
export class AuthAPI {
79
private fm: FilemakerDataAPI;
10+
private accessToken: string | null;
11+
private accessTokenTimestamp: number;
812

913
constructor(fm: FilemakerDataAPI) {
1014
this.fm = fm;
15+
this.accessToken = null;
16+
this.accessTokenTimestamp = 0;
1117
}
1218

1319
/**
@@ -17,6 +23,16 @@ export class AuthAPI {
1723
* @param password
1824
*/
1925
public async login(username: string, password: string): Promise<string> {
26+
const isTimeLimitExceeded =
27+
Date.now() - this.accessTokenTimestamp < TIME_LIMIT;
28+
29+
// Use the cached access token if time limit hasn't been exceeded
30+
if (!isTimeLimitExceeded && this.accessToken) {
31+
this.accessTokenTimestamp = Date.now();
32+
return this.accessToken;
33+
}
34+
35+
// Continue with BASIC auth if no cached access token
2036
if (!username || !password) {
2137
throw new Error('Invalid login credentials');
2238
}
@@ -41,7 +57,12 @@ export class AuthAPI {
4157
throw new Error('Unable to authenticate');
4258
}
4359

44-
return response.response.token as string;
60+
const accessToken = response.response.token;
61+
62+
this.accessToken = accessToken;
63+
this.accessTokenTimestamp = Date.now();
64+
65+
return accessToken as string;
4566
}
4667

4768
public async logout(authToken: string) {

src/index.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,6 @@ export class FilemakerDataAPI {
8686
config: config ? config.axios : undefined,
8787
});
8888

89-
await this.auth.logout(accessToken);
90-
9189
return response;
9290
}
9391

0 commit comments

Comments
 (0)