export class ResponseError extends Error {
  response: Response;
  status: number;

  constructor(response: Response, message?: string) {
    super(message);
    this.name = 'ResponseError';
    this.response = response;
    this.status = response.status;
  }
}

export interface PostDataHTTPOptions extends Omit<RequestInit, 'body'> {
  url: string;
  method?: 'POST' | 'PUT' | 'PATCH';
}

export type PostDataFetcher = (input: string, init: RequestInit) => Promise<Response>;

export async function postData(
  { url, method = 'POST', ...httpOptions }: PostDataHTTPOptions,
  data: RequestInit['body'],
  fetcher: PostDataFetcher = fetch,
) {
  const response = await fetcher(url, {
    method,
    body: data,
    ...httpOptions,
  });

  if (!response.ok) {
    throw new ResponseError(response, response.statusText);
  }

  return response;
}
