Created
February 1, 2022 20:40
-
-
Save kobzarvs/c015284efb0e1cc00c96b6cf57acce65 to your computer and use it in GitHub Desktop.
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 { attach, createEffect } from 'effector'; | |
import { HTTP_METHOD, RequestFxParams, ResponseError, User } from './types'; | |
import { $session } from '../models/session'; | |
export const GET = 'GET'; | |
export const POST = 'POST'; | |
export const PUT = 'PUT'; | |
export const DELETE = 'DELETE'; | |
const URL = 'https://api.realworld.io/api'; | |
export const createRequestEffect = <T, R>(method: HTTP_METHOD, endpoint: string) => { | |
const effect = createEffect<RequestFxParams, R, ResponseError>(async (options) => { | |
const { token, ...params } = options; | |
const response = await fetch(`${URL}${endpoint}`, { | |
method, | |
headers: { | |
'Content-Type': 'application/json;charset=utf-8', | |
'Authorization': `Token ${token}`, | |
}, | |
...params, | |
}); | |
const json = await response.json(); | |
if (response.ok) { | |
return json; | |
} else { | |
throw { | |
status: response.status, | |
text: response.statusText, | |
errors: json.errors, | |
}; | |
} | |
}); | |
const mapParams = (params: T, session: User) => { | |
const options: RequestFxParams = { | |
token: session.token, | |
}; | |
if (method !== GET) { | |
options.body = JSON.stringify(params); | |
} | |
return options; | |
}; | |
return attach({ | |
source: $session, | |
mapParams, | |
effect, | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment