Skip to content

Instantly share code, notes, and snippets.

@walerian777
Last active September 2, 2022 02:24
Show Gist options
  • Save walerian777/b0b63ad4537ebca16cba5e9a9357840f to your computer and use it in GitHub Desktop.
Save walerian777/b0b63ad4537ebca16cba5e9a9357840f to your computer and use it in GitHub Desktop.
Data fetching it typescript
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)
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