import useSWR, { SWRResponse } from "swr";
import config from './config';
/**
 * 请求封装
 * @param url 请求url
 * @param method 请求方法类型
 * @param data 请求的参数
 * @returns Promise<Response>
 */
export default function request(url: string, method: String = 'get', data?: any): SWRResponse {
  let options = {};

  switch (method.toLowerCase()) {
    case 'get':
      let params = new URLSearchParams();
      if (data) {
        Object.keys(data).forEach((key) => {
          params.append(key, data[key]);
        })

        url += params;
      }
      break;

    case 'post':
      options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      }
      break;
  }

  const fetcher = (url:string) => fetch(config.baseUrl + url, options)
    .then((r) => r.json())
    .then((data) => {
      return data;
    });

  return useSWR(url, fetcher)
}