♻️🎨 connector: light cleanup, load (#525)

renaming logger, adding health endpoint, working with old API,
removing aggressive force save stuff, missing forgotten files etc,
documentation
This commit is contained in:
Eric Doughty-Papassideris
2024-07-10 01:41:00 +02:00
committed by ericlinagora
parent 16dbf8077b
commit 92aad866d5
17 changed files with 300 additions and 172 deletions
@@ -5,31 +5,34 @@ import {
IApiServiceApplicationTokenResponse,
} from '@/interfaces/api.interface';
import axios, { Axios, AxiosRequestConfig, AxiosResponse } from 'axios';
import { CREDENTIALS_ENDPOINT, CREDENTIALS_ID, CREDENTIALS_SECRET, ONLY_OFFICE_SERVER } from '@config';
import loggerService from './logger.service';
import { CREDENTIALS_ENDPOINT, CREDENTIALS_ID, CREDENTIALS_SECRET } from '@config';
import logger from '../lib/logger';
import * as Utils from '@/utils';
import { PolledThingieValue } from '@/lib/polled-thingie-value';
/** Client for the Twake Drive backend API on behalf of the plugin (or provided token in parameters) */
/**
* Client for the Twake Drive backend API on behalf of the plugin (or provided token in parameters).
* Periodically updates authorization and adds to requests.
*/
class ApiService implements IApiService {
private axios: Axios;
private initialized: Promise<string>;
private readonly poller: PolledThingieValue<Axios>;
constructor() {
this.initialized = this.refreshToken();
this.initialized.catch(error => {
loggerService.error('failed to init API', error);
});
this.poller = new PolledThingieValue('Refresh Twake Drive token', async () => this.refreshToken(), 1000 * 60); //TODO: should be Every 10 minutes
}
setInterval(() => {
this.initialized = this.refreshToken();
loggerService.info('Refreshing token 🪙');
}, 1000 * 60); //TODO: should be Every 10 minutes
public async hasToken() {
return (await this.poller.latestValueWithTry()) !== undefined;
}
private requireAxios() {
return this.poller.requireLatestValueWithTry('Token Kind 538 not ready');
}
public get = async <T>(params: IApiServiceRequestParams<T>): Promise<T> => {
const { url, token, responseType, headers } = params;
await this.initialized;
const axiosWithToken = await this.requireAxios();
const config: AxiosRequestConfig = {};
@@ -43,35 +46,35 @@ class ApiService implements IApiService {
if (responseType) {
config['responseType'] = responseType;
}
return await this.axios.get(url, config);
return await axiosWithToken.get(url, config);
};
public post = async <T, R>(params: IApiServiceRequestParams<T>): Promise<R> => {
const { url, payload, headers } = params;
await this.initialized;
const axiosWithToken = await this.requireAxios();
try {
return await this.axios.post(url, payload, {
return await axiosWithToken.post(url, payload, {
headers: {
...headers,
},
});
} catch (error) {
loggerService.error('Failed to post: ', error.message);
logger.error('Failed to post to Twake drive: ', error.stack);
this.refreshToken();
}
};
private handleErrors = (error: any): Promise<any> => {
loggerService.error('Failed Request', error.message);
logger.error('Failed Request to Twake drive', error.stack);
return Promise.reject(error);
};
private handleResponse = <T>({ data }: AxiosResponse): T => data;
private refreshToken = async (): Promise<string> => {
private refreshToken = async (): Promise<Axios> => {
try {
const response = await axios.post<IApiServiceApplicationTokenRequestParams, { data: IApiServiceApplicationTokenResponse }>(
Utils.joinURL([CREDENTIALS_ENDPOINT, '/api/console/v1/login']),
@@ -92,25 +95,24 @@ class ApiService implements IApiService {
},
} = response.data;
this.axios = axios.create({
const axiosWithToken = axios.create({
baseURL: CREDENTIALS_ENDPOINT,
headers: {
Authorization: `Bearer ${value}`,
},
});
this.axios.interceptors.response.use(this.handleResponse, this.handleErrors);
axiosWithToken.interceptors.response.use(this.handleResponse, this.handleErrors);
return value;
return axiosWithToken;
} catch (error) {
loggerService.error('failed to get application token', error.message);
loggerService.info('Using token ', CREDENTIALS_ID, CREDENTIALS_SECRET);
loggerService.info(`POST ${CREDENTIALS_ENDPOINT.replace(/\/$/, '')}/api/console/v1/login`);
loggerService.info(`Basic ${Buffer.from(`${CREDENTIALS_ID}:${CREDENTIALS_SECRET}`).toString('base64')}`);
logger.error('failed to get application token from Twake drive', error.stack);
logger.info('Using token ', CREDENTIALS_ID, CREDENTIALS_SECRET);
logger.info(`POST ${CREDENTIALS_ENDPOINT.replace(/\/$/, '')}/api/console/v1/login`);
logger.info(`Basic ${Buffer.from(`${CREDENTIALS_ID}:${CREDENTIALS_SECRET}`).toString('base64')}`);
throw Error(error);
}
};
}
export default new ApiService();