npm.io
1.0.0 • Published 3 years ago

@tectonique/api-standards

Licence
MIT
Version
1.0.0
Deps
1
Size
32 kB
Vulns
1
Weekly
0



Logo of library api-standards


npm

API Standards

This library provides utilities for creating end to end type safe APIs.

The library advocates:

Table of contents

NPM Package

Installation

Using npm:

npm i @tectonique/api-standards

Using yarn:

yarn add @tectonique/api-standards

Goal

The goal of the library is to help you create type safe code like this:

import { ResponseEnvelopes } from "@tectonique/api-standards"

// Import response and error (problem detail) types
import { ProblemDetailSuperType } from "@backend/ProblemDetailSuperType"
import { API_GetUsers_Response } from "@backend/ApiResponses"

// Make the API call
const data = await axios.get("/api/users")
  .then((response) => response.data)
  .catch((error) => error.response.data)

// Check and inspect envelope
if ( ResponseEnvelopes.isEnvelope(data) ) {
  const envelope = data as ResponseEnvelopes.Envelope<
    ProblemDetailSuperType,
    API_GetUsers_Response
  >
  
  // Success envelope ... obviously ^^
  if ( envelope.success ) {
    console.log(
      "User email adresses:",
      envelope.payload.map(user => user.email).join(', ')
    )
    
  // Problem detail
  } else if ( envelope.type === "unauthorized" ) {
    throw new Error("Session expired")
    
  } else {
    throw new Error("Unhandled problem detail: " + envelope.type)
  }
  
} else {
  throw new Error("Didn't receive an envelope")
}

Documentation

Problem Details

Response Envelopes

Changelog

Author

Peter Kuhmann
GitHub: hedgehogs-mind


Tectonique

Tectonique logo

Keywords