-
Notifications
You must be signed in to change notification settings - Fork 5
/
SecurityDataStorage.ts
50 lines (41 loc) · 1.41 KB
/
SecurityDataStorage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import fs from "fs-extra";
import { ISecurityDataStorage, Tokens } from "../src";
import { SecurityDataFilter } from "../src/types/SecurityDataFilter";
/**
* A SecurityData model. This can be a record in a database or a file.
*/
export type SecurityDataItem = Tokens & {
etsyUserId: number;
};
/**
* This is an example of how to implement ISecurityDataStorage interface.
* You can use this class to store security data in a file or in a database.
*/
export class SecurityDataStorage implements ISecurityDataStorage {
filepath = "./examples/security-data.json";
async storeAccessToken(filter: SecurityDataFilter, accessToken: Tokens) {
const all = (await fs.readJson(this.filepath)) as SecurityDataItem[];
const etsyUserId = parseInt(accessToken.accessToken.split(".")[0]);
const index = all.findIndex((item) => item.etsyUserId === etsyUserId);
if (index === -1) {
all.push({
etsyUserId,
...accessToken,
});
} else {
all[index] = {
etsyUserId,
...accessToken,
};
}
await fs.writeJSON(this.filepath, all, { spaces: 2 });
}
async findAccessToken(
filter: SecurityDataFilter
): Promise<Tokens | undefined> {
if (!fs.existsSync(this.filepath)) return undefined;
const all =
((await fs.readJson(this.filepath)) as SecurityDataItem[]) || [];
return all.find((item) => item.etsyUserId === filter.etsyUserId);
}
}