Skip to content

Instantly share code, notes, and snippets.

@ever-dev
Created August 21, 2020 15:29
Show Gist options
  • Save ever-dev/6912252669245843051f195518362f58 to your computer and use it in GitHub Desktop.
Save ever-dev/6912252669245843051f195518362f58 to your computer and use it in GitHub Desktop.
Http Client to fetch urls
type THttpMethod = "GET" | "POST" | "PUT" | "DELETE";
export const httpClient = (
url: string,
method: THttpMethod = "GET",
data: any = {}
) => {
const params: { [i: string]: any } = {
method,
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
};
if (method !== "GET") {
params.body = JSON.stringify(data);
} else {
url = `${url}?${Object.keys(data)
.map(key => `${key}=${data[key]}`)
.join("&")}`;
}
return new Promise<any>((resolve, reject) => {
fetch(url, params).then(res => {
if (res.ok) {
res.json().then(resolve);
} else {
res.json().then(reject);
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment