~cytrogen/masto-fe

ref: 110c8fb8ccb1363f649d3eb30ca822f415145e6a masto-fe/app/javascript/mastodon/api.ts -rw-r--r-- 1.4 KiB
110c8fb8 — Sqx. Flann [bugfix] account for data structure change in instance API fallback (#63) 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import type { AxiosResponse, RawAxiosRequestHeaders } from 'axios';
import axios from 'axios';
import LinkHeader from 'http-link-header';

import ready from './ready';
import type { GetState } from './store';

export const getLinks = (response: AxiosResponse) => {
  const value = response.headers.link as string | undefined;

  if (!value) {
    return new LinkHeader();
  }

  return LinkHeader.parse(value);
};

const csrfHeader: RawAxiosRequestHeaders = {};

const setCSRFHeader = () => {
  const csrfToken = document.querySelector<HTMLMetaElement>(
    'meta[name=csrf-token]',
  );

  if (csrfToken) {
    csrfHeader['X-CSRF-Token'] = csrfToken.content;
  }
};

void ready(setCSRFHeader);

const authorizationHeaderFromState = (getState?: GetState) => {
  const accessToken =
    getState && (getState().meta.get('access_token', '') as string);

  if (!accessToken) {
    return {};
  }

  return {
    Authorization: `Bearer ${accessToken}`,
  } as RawAxiosRequestHeaders;
};

// eslint-disable-next-line import/no-default-export
export default function api(getState: GetState) {
  return axios.create({
    headers: {
      ...csrfHeader,
      ...authorizationHeaderFromState(getState),
    },

    transformResponse: [
      function (data: unknown) {
        try {
          return JSON.parse(data as string) as unknown;
        } catch {
          return data;
        }
      },
    ],
  });
}