solid-realworld icon indicating copy to clipboard operation
solid-realworld copied to clipboard

Typescript version of this?

Open m1thrandir225 opened this issue 2 years ago • 1 comments

Getting started with solid, and wanted to create something similar but I have been struggling to get the createAgent.js file converted to typescript.

My current problem is: const headers = {}, body = {}, opts = { method, headers, body }; if (data !== undefined) { headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(data); } But, headers["Content-type"] has this error, which I don't know how to fix, as u can't exactly get the headers type from the fetch api. Element implicitly has an 'any' type because expression of type '"Content-Type"' can't be used to index type '{}'. Property 'Content-Type' does not exist on type '{}'.

I know is kinda dumb but any help would be appreciated

m1thrandir225 avatar Jan 21 '23 00:01 m1thrandir225

It should be something like this


type HttpMethod = "get" | "post" | "put" | "delete" | "patch";

async function send<T>(
  method: HttpMethod ,
  url: string,
  data?: any,
): Promise<T>
async function send<T>(
  method: HttpMethod ,
  url: string,
  data: any,
  resKey: keyof T
): Promise<T[typeof resKey]>
async function send<T>(
  method: HttpMethod ,
  url: string,
  data?: any,
  resKey?: any
): Promise<T> {
  const headers: HeadersInit = {};
  const opts: RequestInit = { method, headers };

  if (data !== undefined) {
    headers["Content-Type"] = "application/json";
    opts.body = JSON.stringify(data);
  }

  if (state.token) {
    headers["Authorization"] = `Token ${state.token}`;
  }

  try {
    const response = await fetch(API_ROOT + url, opts);
    const json: T = await response.json();

    return resKey ? json[resKey] : json;
  } catch (err) {
    if (err && err.response && err.response.status === 401) {
      actions.logout();
    }
    return err;
  }
}

You can try to use Chat Openai for such stuff. It works pretty well 👍

SonyStone avatar Jan 31 '23 02:01 SonyStone