Skip to content

Instantly share code, notes, and snippets.

@kobzarvs
Created February 1, 2022 20:40
Show Gist options
  • Save kobzarvs/c015284efb0e1cc00c96b6cf57acce65 to your computer and use it in GitHub Desktop.
Save kobzarvs/c015284efb0e1cc00c96b6cf57acce65 to your computer and use it in GitHub Desktop.
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