GithubHelp home page GithubHelp logo

fetchclient's Introduction

FetchClient CI JSR

FetchClient is a library that makes it easier to use the fetch API for JSON APIs. It provides the following features:

  • Makes fetch easier to use for JSON APIs
  • Automatic model validation
  • Caching
  • Middleware
  • Problem Details support
  • Option to parse dates in responses

Install

npm install --save @exceptionless/fetchclient

Docs

API Documentation

Usage

Get a typed JSON response:

import { FetchClient } from '@exceptionless/fetchclient';

type Products = {
  products: Array<{ id: number; name: string }>;
};

const client = new FetchClient();
const response = await client.getJSON<Products>(
  `https://dummyjson.com/products/search?q=iphone&limit=10`,
);

const products = response.data;

Get a typed JSON response using a function:

import { useFetchClient } from '@exceptionless/fetchclient';

type Products = {
  products: Array<{ id: number; name: string }>;
};

const response = await useFetchClient().getJSON<Products>(
  `https://dummyjson.com/products/search?q=iphone&limit=10`,
);

const products = response.data;

Use a model validator:

import { FetchClient, setModelValidator } from '@exceptionless/fetchclient';

setModelValidator(async (data: object | null) => {
  // use zod or any other validator
  const problem = new ProblemDetails();
  const d = data as { password: string };
  if (d?.password?.length < 6) {
    problem.errors.password = [
      "Password must be longer than or equal to 6 characters.",
    ];
  }
  return problem;
});

const client = new FetchClient();
const data = {
  email: "test@test",
  password: "test",
};

const response = await client.postJSON(
  "https://jsonplaceholder.typicode.com/todos/1",
  data,
);

if (!response.ok) {
  // check response problem
  console.log(response.problem.detail);
}

Use caching:

import { FetchClient } from '@exceptionless/fetchclient';

type Todo = { userId: number; id: number; title: string; completed: boolean };

const client = new FetchClient();
const response = await client.getJSON<Todo>(
  `https://jsonplaceholder.typicode.com/todos/1`,
  {
    cacheKey: ["todos", "1"],
    cacheDuration: 1000 * 60, // expires in 1 minute
  }
);

// invalidate programmatically
client.cache.delete(["todos", "1"]);

Use middleware:

import { FetchClient, useMiddleware } from '@exceptionless/fetchclient';

type Products = {
  products: Array<{ id: number; name: string }>;
};

useMiddleware(async (ctx, next) => {
  console.log('starting request')
  await next();
  console.log('completed request')
});

const client = new FetchClient();
const response = await client.getJSON<Products>(
  `https://dummyjson.com/products/search?q=iphone&limit=10`,
);

Also, take a look at the tests:

FetchClient Tests

License

MIT © Exceptionless

fetchclient's People

Contributors

ejsmith avatar

Stargazers

Connor Walsh avatar Mathew D'Amico avatar

Watchers

Mathew D'Amico avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.