1.0.1 • Published 1 year ago

@vukovicpavle/tomato-api-factory v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

🍅 Api factory

Create endpoints with ease.

Installation

npm install @vukovicpavle/tomato-api-factory

Usage

const api = new ApiFactory({
  baseUrl: "https://jsonplaceholder.typicode.com",
  config: {
    headers: {
      "Content-Type": "application/json",
    },
  },
  onRequest: (config) => {
    console.log("onRequest", config);
    return config;
  },
  onResponse: (response) => {
    console.log("onResponse", response);
    return response;
  },
});

type Post = {
  userId: number;
  id: number;
  title: string;
};

const posts = api.createEndpoint({
  url: "/posts",
  custom: {
    getPostByUserId: (userId: number) => {
      return api.get<Post[]>(`/posts?userId=${userId}`);
    },
  },
});

posts.findAll<Post[]>().then((posts) => {
  console.log(posts);
});

posts.findOne<Post>("1").then((post) => {
  console.log(post);
});

posts.custom.getPostByUserId(1).then((posts) => {
  console.log(posts);
});

API

ApiFactory

Parameters

NameTypeDescriptionRequiredDefault
configobjectApiFactory configurationfalse{}
config
NameTypeDescriptionRequiredDefault
baseUrlstringBase URL for all endpointsfalse""
configobjectAxios configurationfalse{}
onRequestfunctionFunction that is called before each requestfalseundefined
onResponsefunctionFunction that is called after each responsefalseundefined

Returns

TypeDescription
objectInstance of ApiFactory

Endpoint

Parameters

NameTypeDescriptionRequiredDefault
configobjectEndpoint configurationfalse{}
config
NameTypeDescriptionRequiredDefault
urlstringURL for endpointtrue""
configobjectAxios configurationfalse{}
customobjectCustom methods for endpointfalse{}

Returns

TypeDescription
objectInstance of Endpoint
1.0.1

1 year ago

1.0.0

1 year ago