reactredux/webapi/ClientApp/src/restClient.ts

73 lines
1.2 KiB
TypeScript

import { Params, RequestModel } from "./models/abstractions"
interface FetchData {
status: number,
text: string
}
const Post = () => {
}
const Get = async <T>(apiUrl: string, pathParams?: Params, searchParams?: Params): Promise<T | null> => {
const url = new URL(apiUrl)
if(pathParams) {
Object.keys(pathParams).forEach(key => {
if (typeof(pathParams[key]) !== undefined) {
url.pathname += `/${pathParams[key]}`
}
})
}
if(searchParams) {
Object.keys(searchParams).forEach(key => {
if (typeof(searchParams[key]) !== undefined) {
url.searchParams.append(key, searchParams[key] as string)
}
})
}
const requestParams = {
method: 'GET',
headers: { 'accept': 'application/json', 'content-type': 'application/json' },
}
const fetchData = await fetch(url.toString(), requestParams)
.then(async fetchData => {
return {
status: fetchData.status,
text: await fetchData.text()
}
})
.catch(err => {
console.log(err)
})
if (fetchData?.text)
return JSON.parse((fetchData as FetchData).text) as T
return null
}
const Put = () => {
}
const Delete = () => {
}
export {
Post,
Get,
Put,
Delete
}