refactor: Use http client for slack authentication

This commit is contained in:
Faruk AYDIN
2022-07-17 00:44:47 +03:00
parent 4237972c86
commit e9ffb7ef82

View File

@@ -1,22 +1,38 @@
import type { IAuthentication, IApp, IJSONObject } from '@automatisch/types'; import type { IAuthentication, IApp, IJSONObject } from '@automatisch/types';
import { WebClient } from '@slack/web-api'; import HttpClient from '../../helpers/http-client';
import qs from 'qs';
export default class Authentication implements IAuthentication { export default class Authentication implements IAuthentication {
appData: IApp; appData: IApp;
connectionData: IJSONObject; connectionData: IJSONObject;
client: WebClient; client: HttpClient;
static requestOptions: IJSONObject = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};
constructor(appData: IApp, connectionData: IJSONObject) { constructor(appData: IApp, connectionData: IJSONObject) {
this.client = new WebClient(); this.client = new HttpClient({ baseURL: 'https://slack.com/api' });
this.connectionData = connectionData; this.connectionData = connectionData;
this.appData = appData; this.appData = appData;
} }
async verifyCredentials() { async verifyCredentials() {
const { bot_id: botId, user: screenName } = await this.client.auth.test({ const response = await this.client.post(
token: this.connectionData.accessToken as string, '/auth.test',
}); qs.stringify({ token: this.connectionData.accessToken }),
Authentication.requestOptions
);
if (response.data.ok === false) {
throw new Error(
`Error occured while verifying credentials: ${response.data.error}.(More info: https://api.slack.com/methods/auth.test#errors)`
);
}
const { bot_id: botId, user: screenName } = response.data;
return { return {
botId, botId,
@@ -27,9 +43,11 @@ export default class Authentication implements IAuthentication {
async isStillVerified() { async isStillVerified() {
try { try {
await this.client.auth.test({ await this.client.post(
token: this.connectionData.accessToken as string, '/auth.test',
}); qs.stringify({ token: this.connectionData.accessToken }),
Authentication.requestOptions
);
return true; return true;
} catch (error) { } catch (error) {