tink/ts/tink.classes.tinkaccount.ts

83 lines
2.3 KiB
TypeScript
Raw Permalink Normal View History

2022-02-15 15:51:16 +00:00
import * as plugins from './tink.plugins';
2022-02-18 11:55:56 +00:00
import { TinkUser } from './tink.classes.tinkuser'
2022-02-15 15:51:16 +00:00
export class TinkAccount {
private clientId: string;
private clientSecret: string;
2022-02-18 11:55:56 +00:00
private apiBaseUrl: string = 'https://api.tink.com';
2022-02-15 15:51:16 +00:00
constructor(clientIdArg: string, clientSecretArg: string) {
this.clientId = clientIdArg;
this.clientSecret = clientSecretArg;
}
2022-02-15 22:50:37 +00:00
public async getTinkHealthyBoolean(): Promise<boolean> {
const response = await plugins.smartrequest.request(
'https://api.tink.com/api/v1/monitoring/healthy',
{}
);
2022-02-15 15:51:16 +00:00
return response.body === 'ok';
}
// the request method for tink respecting platform specific stuff
// e.g. certain headers if needed
2022-02-18 11:55:56 +00:00
public async request(optionsArg: {
2022-02-15 22:50:37 +00:00
urlArg: string,
methodArg: 'POST' | 'GET',
scopeArg: string,
2022-02-18 11:55:56 +00:00
payloadArg: any,
externalUserId: string
}) {
2022-02-15 15:51:16 +00:00
// check health
if (!(await this.getTinkHealthyBoolean())) {
2022-02-17 10:54:44 +00:00
throw new Error('TINK is not healthy right now. Please try again later.');
2022-02-15 15:51:16 +00:00
} else {
console.log('tink is healthy, continuing...');
}
// lets get an accessToken for the request
2022-02-15 22:50:37 +00:00
const response = await plugins.smartrequest.postFormDataUrlEncoded(
2022-02-18 11:55:56 +00:00
`${this.apiBaseUrl}/api/v1/oauth/token`,
2022-02-15 22:50:37 +00:00
{},
[
{
key: 'client_id',
content: this.clientId,
},
{
key: 'client_secret',
content: this.clientSecret,
},
{
key: 'grant_type',
content: 'client_credentials',
},
{
key: 'scope',
2022-02-18 11:55:56 +00:00
content: optionsArg.scopeArg,
2022-02-15 22:50:37 +00:00
},
]
);
2022-02-18 11:55:56 +00:00
if (response.statusCode !== 200) {
throw new Error('there was an error aquiring an access token.');
}
const accessToken = response.body.access_token;
const response2 = await plugins.smartrequest.request(`${this.apiBaseUrl}${optionsArg.urlArg}`, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
method: optionsArg.methodArg,
requestBody: JSON.stringify(optionsArg.payloadArg)
})
console.log(response2.statusCode);
return response2.body;
}
public async createTinkUser(externalUserIdArg: string) {
const tinkuser = await TinkUser.createNewTinkUser(this, externalUserIdArg);
2022-02-15 22:50:37 +00:00
}
}