bigbuffet-rw/app/soapbox/api.js

40 lines
931 B
JavaScript
Raw Normal View History

2020-03-27 13:59:38 -07:00
'use strict';
import axios from 'axios';
import LinkHeader from 'http-link-header';
2021-03-31 12:47:54 -07:00
import { getAccessToken, getAppToken } from 'soapbox/utils/auth';
2020-03-27 13:59:38 -07:00
export const getLinks = response => {
const value = response.headers.link;
if (!value) return { refs: [] };
2020-03-27 13:59:38 -07:00
return LinkHeader.parse(value);
};
const getToken = (getState, authType) => {
const state = getState();
2021-03-31 12:47:54 -07:00
return authType === 'app' ? getAppToken(state) : getAccessToken(state);
};
2020-04-29 12:06:26 -07:00
2021-03-31 12:47:54 -07:00
const maybeParseJSON = data => {
try {
return JSON.parse(data);
} catch(Exception) {
return data;
}
};
2020-04-29 12:06:26 -07:00
2021-03-31 12:47:54 -07:00
export const baseClient = accessToken => {
2020-04-04 13:28:57 -07:00
return axios.create({
2020-06-09 12:45:48 -07:00
headers: Object.assign(accessToken ? {
2020-04-29 12:06:26 -07:00
'Authorization': `Bearer ${accessToken}`,
2020-04-04 13:28:57 -07:00
} : {}),
2021-03-31 12:47:54 -07:00
transformResponse: [maybeParseJSON],
2020-04-04 13:28:57 -07:00
});
};
2021-03-31 12:47:54 -07:00
export default (getState, authType = 'user') => {
const accessToken = getToken(getState, authType);
return baseClient(accessToken);
};