0.0.10 • Published 1 year ago

@tectonique/api-standards-client v0.0.10

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

🌩 API Standards – Client

This library is based on tectonique/api-standards 🔗.

It provides client utilities to make API requests and error handling 100% type safe.

Currently, type wrappers are provided for:

📖 Table of contents

📦 NPM Package

💾 Installation

Using npm:

npm i @tectonique/api-standards-client

Using yarn:

yarn add @tectonique/api-standards-client

🏁 Goal

When you have

You want to perform such 100% type safe API calls:

const createUserEnvelope = await MyApi.createUser(
  "theo@testing.com",
  "Theo Tester"
).catch(createProblemDetailHandler(pd => {
  if (createUserEnvelope.type === "response-not-an-envelope") {
    alert("Response is not an envelope!");
  }
}));

console.log("User id: ", createUserEnvelope.payload.id);

📑 Documentation

💠 Axios with type safety

  • Import your backend request/query/response types.
  • Import your backend Problem Detail Super Type.
  • Create a typable axios instance with makeAxiosTypeSafe(axiosInstance).
  • Create your custom API instance with methods that use get|post|put|patch|delete of the typeable axios instance.

An example: Here is an example:

import axios from "axios";
import { ProblemDetailSuperType } from "@backend/ProblemDetailSuperType"
import { createTypeSafeAxios, ClientProblemDetailSuperType } from "@tectonique/api-standards-client";

type Create_User_Body = {
  email: string;
  name: string;
};

type Create_User_Response = {
  id: string;
};

const {
  verbs,
  createProblemDetailHandler,
  handleProblemDetail
} = createTypeSafeAxios<ProblemDetailSuperType | ClientProblemDetailSuperType>(axios);

const MyApi = {
  createUser: (email: string, name: string) =>
    verbs.post<Create_User_Response, Create_User_Body, undefined>(
      "/users",
      { email, name }
    ),
};

const createUserEnvelope = await MyApi.createUser(
  "theo@testing.com",
  "Theo Tester"
).catch(createProblemDetailHandler(pd => {
  if (createUserEnvelope.type === "response-not-an-envelope") {
    alert("Response is not an envelope!");
  }
}));

console.log("User id: ", createUserEnvelope.payload.id);

// OR wit try catch + await
try {
  const createUserEnvelope = await MyApi.createUser(
    "theo@testing.com",
    "Theo Tester"
  )

  console.log("User id: ", createUserEnvelope.payload.id);
} catch ( error ) {
  // await is important to catch rethrown non problem detail errors!
  await handleProblemDetail(error, (pd) => {
    if (createUserEnvelope.type === "response-not-an-envelope") {
      alert("Response is not an envelope!");
    }
  })  
}

📜 Changelog

🦔 Author

0.0.10

1 year ago

0.0.9

1 year ago

0.0.8

1 year ago

0.0.7

1 year ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago