-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
64 lines (56 loc) · 1.69 KB
/
index.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import NyplApiClient from "@nypl/nypl-data-api-client"
import { appConfig } from "../../config/config"
import { kmsDecryptCreds } from "../kms"
interface KMSCache {
clients: string[]
id: string
secret: string
}
const appEnvironment = appConfig.environment
const encryptedClientId = process.env.PLATFORM_API_CLIENT_ID
const encryptedClientSecret = process.env.PLATFORM_API_CLIENT_SECRET
const creds = [encryptedClientId, encryptedClientSecret]
const CACHE: KMSCache = { clients: [], secret: null, id: null }
export class NyplApiClientError extends Error {
constructor(message: string) {
super()
this.message = "Error building NYPL data api client: " + message
}
}
const nyplApiClient = async ({
apiName = "platform",
version = "v0.1",
} = {}) => {
if (CACHE.clients[`${apiName}${version}`]) {
return CACHE.clients[`${apiName}${version}`]
}
const baseUrl =
appConfig.apiEndpoints[apiName][appEnvironment] + "/" + version
let decryptedId: string
let decryptedSecret: string
if (CACHE.secret && CACHE.id) {
decryptedId = CACHE.id
decryptedSecret = CACHE.secret
} else {
try {
;[decryptedId, decryptedSecret] = await kmsDecryptCreds(creds)
CACHE.id = decryptedId
CACHE.secret = decryptedSecret
} catch (exception) {
throw new NyplApiClientError("Error decrypting creds")
}
}
try {
const nyplApiClient = new NyplApiClient({
base_url: baseUrl,
oauth_key: decryptedId,
oauth_secret: decryptedSecret,
oauth_url: appConfig.urls.tokenUrl,
})
CACHE.clients[apiName] = nyplApiClient
return nyplApiClient
} catch (error) {
throw new NyplApiClientError(error.message)
}
}
export default nyplApiClient