Created
August 21, 2020 15:29
-
-
Save ever-dev/6912252669245843051f195518362f58 to your computer and use it in GitHub Desktop.
Http Client to fetch urls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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