gitea源码

fetch.ts 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import {isObject} from '../utils.ts';
  2. import type {RequestOpts} from '../types.ts';
  3. const {csrfToken} = window.config;
  4. // safe HTTP methods that don't need a csrf token
  5. const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
  6. // fetch wrapper, use below method name functions and the `data` option to pass in data
  7. // which will automatically set an appropriate headers. For json content, only object
  8. // and array types are currently supported.
  9. export function request(url: string, {method = 'GET', data, headers = {}, ...other}: RequestOpts = {}): Promise<Response> {
  10. let body: string | FormData | URLSearchParams;
  11. let contentType: string;
  12. if (data instanceof FormData || data instanceof URLSearchParams) {
  13. body = data;
  14. } else if (isObject(data) || Array.isArray(data)) {
  15. contentType = 'application/json';
  16. body = JSON.stringify(data);
  17. }
  18. const headersMerged = new Headers({
  19. ...(!safeMethods.has(method) && {'x-csrf-token': csrfToken}),
  20. ...(contentType && {'content-type': contentType}),
  21. });
  22. for (const [name, value] of Object.entries(headers)) {
  23. headersMerged.set(name, value);
  24. }
  25. return fetch(url, {
  26. method,
  27. headers: headersMerged,
  28. ...other,
  29. ...(body && {body}),
  30. });
  31. }
  32. export const GET = (url: string, opts?: RequestOpts) => request(url, {method: 'GET', ...opts});
  33. export const POST = (url: string, opts?: RequestOpts) => request(url, {method: 'POST', ...opts});
  34. export const PATCH = (url: string, opts?: RequestOpts) => request(url, {method: 'PATCH', ...opts});
  35. export const PUT = (url: string, opts?: RequestOpts) => request(url, {method: 'PUT', ...opts});
  36. export const DELETE = (url: string, opts?: RequestOpts) => request(url, {method: 'DELETE', ...opts});