request.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { GraphQLError } from "graphql";
  2. import { get as get_token } from "./reducers/session";
  3. export const upload = () => {
  4. return {
  5. Authorization: `Bearer ${get_token()}`,
  6. };
  7. };
  8. export const options = (method: string): RequestInit => {
  9. return {
  10. credentials: "include",
  11. headers: {
  12. Authorization: `Bearer ${get_token()}`,
  13. "Content-Type": "application/json; charset=utf-8",
  14. },
  15. mode: "cors",
  16. method,
  17. };
  18. };
  19. export const get = async <R>(path: string): Promise<R> => {
  20. const response = await fetch(path, options("GET"));
  21. const res: R = await response.json();
  22. return res;
  23. };
  24. export const delete_ = async <R>(path: string): Promise<R> => {
  25. const response = await fetch(path, options("DELETE"));
  26. const res: R = await response.json();
  27. return res;
  28. };
  29. export interface IGraphqlResponse<R> {
  30. data?: R;
  31. errors?: GraphQLError[];
  32. }
  33. export const graphql = async <Q, R>(
  34. query: string,
  35. variables: Q
  36. ): Promise<IGraphqlResponse<R>> => {
  37. const res: IGraphqlResponse<R> = await post("/graphql", { query, variables });
  38. return res;
  39. };
  40. // https://github.github.io/fetch/#options
  41. export const post = async <Q, R>(path: string, body: Q): Promise<R> => {
  42. const data = options("POST");
  43. data.body = JSON.stringify(body);
  44. const response = await fetch(path, data);
  45. const res: R = await response.json();
  46. return res;
  47. };
  48. export const patch = <Request, Response>(
  49. path: string,
  50. body: Request
  51. ): Promise<Response> => {
  52. const data = options("PATCH");
  53. data.body = JSON.stringify(body);
  54. return fetch(path, data).then((res) => {
  55. if (res.status === 200) {
  56. return res.json();
  57. }
  58. throw res.text();
  59. });
  60. };
  61. export const put = <Request, Response>(
  62. path: string,
  63. body: Request
  64. ): Promise<Response> => {
  65. const data = options("PUT");
  66. data.body = JSON.stringify(body);
  67. return fetch(path, data).then((res) =>
  68. res.status === 200
  69. ? res.json()
  70. : res.json().then((err) => {
  71. throw err;
  72. })
  73. );
  74. };
  75. export const download = (path: string, name: string) => {
  76. const data = options("GET");
  77. fetch(path, data)
  78. .then((response) => response.blob())
  79. .then((blob) => {
  80. const url = window.URL.createObjectURL(blob);
  81. const a = document.createElement("a");
  82. a.href = url;
  83. a.download = name;
  84. document.body.appendChild(a); // for firefox
  85. a.click();
  86. a.remove();
  87. });
  88. };