Simplified ShlinkApiCLient by using the new simplified authentication approach

This commit is contained in:
Alejandro Celaya
2019-01-10 19:17:15 +01:00
parent b96ea89f90
commit 23af0de34a
2 changed files with 56 additions and 93 deletions

View File

@@ -2,7 +2,6 @@ import qs from 'qs';
import { isEmpty, isNil, reject } from 'ramda';
const API_VERSION = '1';
const STATUS_UNAUTHORIZED = 401;
const buildRestUrl = (url) => url ? `${url}/rest/v${API_VERSION}` : '';
export default class ShlinkApiClient {
@@ -10,98 +9,54 @@ export default class ShlinkApiClient {
this.axios = axios;
this._baseUrl = buildRestUrl(baseUrl);
this._apiKey = apiKey || '';
this._token = '';
}
listShortUrls = (options = {}) =>
this._performRequest('/short-codes', 'GET', options)
.then((resp) => resp.data.shortUrls)
.catch((e) => this._handleAuthError(e, this.listShortUrls, [ options ]));
this._performRequest('/short-urls', 'GET', options)
.then((resp) => resp.data.shortUrls);
createShortUrl = (options) => {
const filteredOptions = reject((value) => isEmpty(value) || isNil(value), options);
return this._performRequest('/short-codes', 'POST', {}, filteredOptions)
.then((resp) => resp.data)
.catch((e) => this._handleAuthError(e, this.createShortUrl, [ filteredOptions ]));
return this._performRequest('/short-urls', 'POST', {}, filteredOptions)
.then((resp) => resp.data);
};
getShortUrlVisits = (shortCode, dates) =>
this._performRequest(`/short-codes/${shortCode}/visits`, 'GET', dates)
.then((resp) => resp.data.visits.data)
.catch((e) => this._handleAuthError(e, this.getShortUrlVisits, [ shortCode, dates ]));
this._performRequest(`/short-urls/${shortCode}/visits`, 'GET', dates)
.then((resp) => resp.data.visits.data);
getShortUrl = (shortCode) =>
this._performRequest(`/short-codes/${shortCode}`, 'GET')
.then((resp) => resp.data)
.catch((e) => this._handleAuthError(e, this.getShortUrl, [ shortCode ]));
this._performRequest(`/short-urls/${shortCode}`, 'GET')
.then((resp) => resp.data);
deleteShortUrl = (shortCode) =>
this._performRequest(`/short-codes/${shortCode}`, 'DELETE')
.then(() => ({}))
.catch((e) => this._handleAuthError(e, this.deleteShortUrl, [ shortCode ]));
this._performRequest(`/short-urls/${shortCode}`, 'DELETE')
.then(() => ({}));
updateShortUrlTags = (shortCode, tags) =>
this._performRequest(`/short-codes/${shortCode}/tags`, 'PUT', {}, { tags })
.then((resp) => resp.data.tags)
.catch((e) => this._handleAuthError(e, this.updateShortUrlTags, [ shortCode, tags ]));
this._performRequest(`/short-urls/${shortCode}/tags`, 'PUT', {}, { tags })
.then((resp) => resp.data.tags);
listTags = () =>
this._performRequest('/tags', 'GET')
.then((resp) => resp.data.tags.data)
.catch((e) => this._handleAuthError(e, this.listTags, []));
.then((resp) => resp.data.tags.data);
deleteTags = (tags) =>
this._performRequest('/tags', 'DELETE', { tags })
.then(() => ({ tags }))
.catch((e) => this._handleAuthError(e, this.deleteTags, [ tags ]));
.then(() => ({ tags }));
editTag = (oldName, newName) =>
this._performRequest('/tags', 'PUT', {}, { oldName, newName })
.then(() => ({ oldName, newName }))
.catch((e) => this._handleAuthError(e, this.editTag, [ oldName, newName ]));
.then(() => ({ oldName, newName }));
_performRequest = async (url, method = 'GET', query = {}, body = {}) => {
if (isEmpty(this._token)) {
this._token = await this._authenticate();
}
return await this.axios({
_performRequest = async (url, method = 'GET', query = {}, body = {}) =>
await this.axios({
method,
url: `${this._baseUrl}${url}`,
headers: { Authorization: `Bearer ${this._token}` },
headers: { 'X-Api-Key': this._apiKey },
params: query,
data: body,
paramsSerializer: (params) => qs.stringify(params, { arrayFormat: 'brackets' }),
}).then((resp) => {
// Save new token
const { authorization = '' } = resp.headers;
this._token = authorization.substr('Bearer '.length);
return resp;
});
};
_authenticate = async () => {
const resp = await this.axios({
method: 'POST',
url: `${this._baseUrl}/authenticate`,
data: { apiKey: this._apiKey },
});
return resp.data.token;
};
_handleAuthError = (e, method, args) => {
// If auth failed, reset token to force it to be regenerated, and perform a new request
if (e.response.status === STATUS_UNAUTHORIZED) {
this._token = '';
return method(...args);
}
// Otherwise, let caller handle the rejection
return Promise.reject(e);
};
}