Last active
September 2, 2022 02:24
-
-
Save walerian777/b0b63ad4537ebca16cba5e9a9357840f to your computer and use it in GitHub Desktop.
Data fetching it typescript
This file contains hidden or 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 HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | |
interface HeadersObject { | |
[key : string] : string | |
} | |
interface FetcherResponse { | |
data : object, | |
headers : HeadersObject | |
} | |
export const request = async ( | |
method : HttpMethod, | |
path : string, | |
body : object = {} | |
) : Promise<FetcherResponse> => { | |
const requestInit : RequestInit = { | |
method: method, | |
headers: defaultHeaders() | |
} | |
if (bodyAllowed(method)) { | |
requestInit.body = JSON.stringify(body) | |
} | |
const response = await fetch(path, requestInit) | |
const data = await response.json() | |
const headers = unpackHeaders(response) | |
return {data, headers} | |
} | |
const defaultHeaders = () : HeadersObject => { | |
return { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json', | |
} | |
} | |
const unpackHeaders = (response : Response) : HeadersObject => { | |
const entries = Array.from(response.headers.entries()) | |
return entries.reduce((acc : HeadersObject, [key, value]) => { | |
acc[key] = value | |
return acc | |
}, {}) | |
} | |
const bodyAllowed = (method : HttpMethod) : boolean => | |
['POST', 'PUT'].includes(method) |
This file contains hidden or 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
import {request} from './Fetcher' | |
interface LoginActionParams { | |
email : string, | |
password : string | |
} | |
export const loginAction = async (params : LoginActionParams) => { | |
const {email, password} = params | |
const {data, headers} = await request( | |
'POST', | |
'http://localhost:3001/api/v1/users/sign_in', | |
{user: {email, password}} | |
) | |
return data | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment