pyrobyte-api-manager
v2.0.7
Published
API manager based on Ky
Downloads
24
Maintainers
Readme
Это миниатюрная библиотека для внутренних нужд построенная поверх ky
Установка
npm install pyrobyte-api-manager
или
yarn add
Установка http-клиента
npm install ky --save-exact
или
npm install axios --save-exact
Использование
import {
ApiManager,
ErrorFactory,
HttpClientKy,
HandleTokenSanctum,
HTTPError,
} from "pyrobyte-api-manager";
import ky, { KyInstance, Options } from "ky";
import { AxiosInstance, AxiosRequestConfig, CreateAxiosDefaults } from "axios";
type ErrorResponse = {
message: string;
errors: Array<string>;
};
const errorFactory: ErrorFactory<ErrorResponse> = async (response) => {
const result = (await response.json()) as ErrorResponse;
return {
message: "Some error message",
errors: result.errors,
};
};
// Должен быть в единственном экземпляре т.е. singleton
const apiManager = new ApiManager<KyInstance, Options, ErrorResponse, Options>(
"https://jsonplaceholder.typicode.com/",
HttpClientKy,
HandleTokenSanctum,
errorFactory
);
const apiManagerAxios = new ApiManager<
AxiosInstance,
AxiosRequestConfig,
ErrorResponse,
CreateAxiosDefaults
>(
"https://jsonplaceholder.typicode.com/",
HttpClientAxios,
HandleTokenOAuthAxios,
errorFactory
);
type Post = {
userId: number;
id: number;
title: string;
body: string;
};
async function getPosts() {
return apiManager.request<Array<Post>>("posts", {
method: "get",
});
}
async function getPost(id: number) {
return apiManagerAxios.request<Post>(`posts/${id}`, {
method: "get",
});
}
//...
async function fetchPosts() {
try {
const response = await getPosts();
setPosts(response.data);
} catch (e) {
if (e instanceof HTTPError) {
const response: ErrorResponse = await e.response.json();
console.log(response.error.message);
}
}
}
async function fetchPost() {
try {
const response = await getPost(1);
console.log("response", response.data);
} catch (e) {
if (e instanceof HTTPError) {
const response: ErrorResponse = await e.response.json();
console.log("axios", response.message);
}
}
}
Использование с кастомным storage
Например, может потребоваться в среде react-native. По умолчанию используется localStorage.
import { Storage } from "pyrobyte-api-manager";
import AsyncStorage from "@react-native-async-storage/async-storage";
const customStorage: Storage = {
async getItem(key) {
return await AsyncStorage.getItem("@storage_Key");
},
async setItem(key, value) {
await AsyncStorage.setItem("@storage_Key", value);
},
async removeItem(key) {
await AsyncStorage.removeItem(key);
},
};
const apiManager = new ApiManager<ErrorResponse>(
//...
{ storage: customStorage }
);