2.0.7 • Published 10 months ago

pyrobyte-api-manager v2.0.7

Weekly downloads
-
License
ISC
Repository
-
Last release
10 months ago

Это миниатюрная библиотека для внутренних нужд построенная поверх 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 }
);
2.0.5

10 months ago

2.0.7

10 months ago

2.0.6

10 months ago

1.0.1

1 year ago

1.0.0

1 year ago

2.0.3

1 year ago

2.0.2

1 year ago

2.0.4

10 months ago

2.0.1

1 year ago

2.0.0

1 year ago

0.0.3

2 years ago

0.0.4

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago