-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (70 loc) · 2.29 KB
/
index.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import NyplApiClient from '@nypl/nypl-data-api-client';
import aws from 'aws-sdk';
import config from '../../../app/data/appConfig';
import logger from '../../../../logger';
const appEnvironment = process.env.APP_ENV || 'production';
const kmsEnvironment = process.env.KMS_ENV || 'encrypted';
let decryptKMS;
let kms;
if (kmsEnvironment === 'encrypted') {
kms = new aws.KMS({
region: 'us-east-1',
});
decryptKMS = (key) => {
const params = {
CiphertextBlob: Buffer.from(key, 'base64'),
};
return new Promise((resolve, reject) => {
kms.decrypt(params, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data.Plaintext.toString());
}
});
});
};
}
const clientId = process.env.clientId || process.env.PLATFORM_API_CLIENT_ID;
const clientSecret = process.env.clientSecret || process.env.PLATFORM_API_CLIENT_SECRET;
const keys = [clientId, clientSecret];
const CACHE = { clients: [] };
function nyplApiClient(options = { apiName: 'platform' }) {
const { apiName } = options;
if (CACHE.clients[apiName]) {
return Promise.resolve(CACHE.clients[apiName]);
}
const baseUrl = config.api[apiName][appEnvironment];
if (kmsEnvironment === 'encrypted') {
return new Promise((resolve, reject) => {
Promise.all(keys.map(decryptKMS))
.then(([decryptedClientId, decryptedClientSecret]) => {
const nyplApiClient = new NyplApiClient({
base_url: baseUrl,
oauth_key: decryptedClientId,
oauth_secret: decryptedClientSecret,
oauth_url: config.tokenUrl,
});
CACHE.clientId = clientId;
CACHE.clientSecret = clientSecret;
CACHE.clients[apiName] = nyplApiClient;
resolve(nyplApiClient);
})
.catch((error) => {
logger.error('ERROR trying to decrypt using KMS.', error);
reject('ERROR trying to decrypt using KMS.', error);
});
});
}
const nyplApiClient = new NyplApiClient({
base_url: baseUrl,
oauth_key: clientId,
oauth_secret: clientSecret,
oauth_url: config.tokenUrl,
});
CACHE.clientId = clientId;
CACHE.clientSecret = clientSecret;
CACHE.clients[apiName] = nyplApiClient;
return Promise.resolve(nyplApiClient);
}
export default nyplApiClient;