• Stars
    star
    107
  • Rank 323,587 (Top 7 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 2 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Not an another HTTP client but a fetch wrapper with fluent API and superpowers

fetchp

npm version npm download license

Table of Contents

What is the fetchp/fetch+?

fetchp is "not an another HTTP client but a fetch wrapper with fluent API and superpowers". The trailing "p" is a means for "plus".

Why? What's the motivation?

fetch is a standard Web API that's already supported by modern browsers, Deno, node.js, bun and etc.

We don't need another HTTP client. Still, a web API's target audience is very broad. APIs like fetch are being designed carefully by the community and organizations to be used by the general public. Any design mistake can cause lots of unrecoverable problems. For this reason, they're keeping it simple and running away from the idea of increasing the extra features they can cover.

So, if you want to use fetch, you may need to wrap it with some extra functionality from time to time. For example, if you call it from a React web project, checking its loading state almost is a must. Or, if you're writing automated tests for your application, you need to mock the fetch API.

This is where fetchp comes into play. It still uses fetch's native implementation that brought you by browsers or runtimes themselves, but in the meantime, it wraps the fetch to provide extra functionality for developers.

Fetchp tries to assemble some tools that are useful and reusable for most of the projects that fetch doesn't provide.

Moreover, since fetchp is a JavaScript module / npm package, it also follows the semantic versioning and its API can be evolved in the future without breaking any project.

Superpowers

  • Fluent API
  • React Hooks API
  • Abortable requests
  • Testing-friendly
  • Mocking response for requests (not just for tests)
  • Setting Base URL
  • Automatic deserialization/parsing by content-types
  • Prefetching and local caching
  • On-demand fetching
  • Fetch status
  • Multiple instances of fetchp
  • TypeScript Type Support

More to come see Todo List section.

Quick start

Execute npm install fetchp or yarn add fetchp to install fetchp and its dependencies into your project directory.

Usage

Basic HTTP Request For Text-Based Data

import { fetchp } from "fetchp";

// you don't need to await request
const req = fetchp.request("GET", "https://www.google.com/");

// you may await data instead...
// once your request is completed, it will return a string
console.log(await req.data);

Basic HTTP Request For JSON Data

import { fetchp } from "fetchp";

const req = fetchp.request("GET", "https://jsonplaceholder.typicode.com/posts");

// since your request will return a json, req.data will return an object
console.log(await req.data);

Caching Requests

import { fetchp, FetchpStatus } from "fetchp";

const doReq = () =>
  fetchp.request(
    "GET",
    "https://jsonplaceholder.typicode.com/posts",
    { cacheRequest: true },
  );

const response1 = doReq();
await new Promise((r) => setTimeout(r, 1000));
const response2 = doReq();

// you can check equality afterwars
assert(await response1.data === await response2.data);

Aborting a Request

import { fetchp, FetchpStatus } from "fetchp";

const req = fetchp.request("GET", "https://jsonplaceholder.typicode.com/posts");

// abort it after 500 milliseconds
setTimeout(() => req.abortController.abort(), 500);

// you can check status afterwars
assert(req.status === FetchpStatus.CANCELED);

Setting a Base URL for Requests

Assume that you're working with a single API on the backend, and you don't want to repeat yourself by concatenating endpoint URL strings in each request you make.

import { fetchp } from "fetchp";

fetchp.setBaseUri("https://jsonplaceholder.typicode.com");

const req = fetchp.request("GET", "/posts");

console.log(await req.data);

Middlewares / Hooks

Assume that you're need to add additional headers to each request you make.

import { fetchp, FetchpHookType } from "fetchp";

fetchp.hooks.add(
  FetchpHookType.BuildRequestHeaders,
  (headers) => headers.set("Authorization", `Bearer ${getIdToken()}`);
);

const response = fetchp.request(
  "GET",
  "https://localhost/api/some-restricted-endpoint"",
);

Middlewares / Hooks (URL Based)

Assume that you're need to observe state changes only for the urls in your filter.

import { fetchp, FetchpHookType } from "fetchp";

fetchp.hooks.addForUrl(
  FetchpHookType.StateChange,
  ["GET", "POST"],
  /^https:\/\/jsonplaceholder\.typicode\.com\//,
  (request, status) =>
    console.log(`[state change] ${request.url} -> ${status}`),
);

const response = fetchp.request(
  "GET",
  "https://jsonplaceholder.typicode.com/todos",
);

On-Demand Fetching

Assume that you don't want to invoke the request immediately. You'll set up an external trigger for this.

import { fetchp } from "fetchp";

const req = fetchp.request("GET", "/posts", { immediate: false });

setTimeout(() => req.exec(), 500);

console.log(await req.data);

Mocking an URL for Request

Assume that your API is not yet built on the backend, and you want to mock its behavior.

import { fetchp } from "fetchp";

const mockContent = { hello: "world" };
const mockResponse = (request) =>
  new Response(
    JSON.stringify(mockContent),
    {
      status: 200,
      statusText: "OK",
      headers: {
        "content-type": "application/json",
      },
    },
  );

fetchp.mocks.add(["GET", "POST"], "/hello", mockResponse);

// mocking is done, let's make a request to the mocked URL
const req = fetchp.request("GET", "/hello");

// it will return { hello: "world" }
console.log(await req.data);

Mocking for Testing (Buggy ATM)

Assume that you want to mock your code without dealing with a test framework and its interfaces / methods. All you need to do is importing fetchp/mock instead of fetchp module.

// just replace fetchp with fetchp/mock
import { fetchp } from "fetchp/mock";

const req = fetchp.request("GET", "/posts");

console.log(await req.data);

Using with React Hooks

import { useFetchp } from "fetchp";

const MyComponent = (props) => {
  const { data, isLoading, error } = useFetchp("GET", "/posts");

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return <div>{JSON.stringify(data)}</div>;
};

Using with React Hooks, mocking for testing

// just replace fetchp with fetchp/mock
import { useFetchp } from "fetchp/mock";

const MyComponent = (props) => {
  const { data, isLoading, error } = useFetchp("GET", "/posts");

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return <div>{JSON.stringify(data)}</div>;
};

Using with React Hooks, manual fetching

import { useEffect } from "react";
import { useFetchp } from "fetchp";

const MyComponent = (props) => {
  const { data, status, isSuccess, doFetch } = useFetchp(
    "GET",
    "/posts",
    false,
  );

  useEffect(() => {
    // fetch data after 500 milliseconds have passed
    setTimeout(() => doFetch(), 500);
  }, []);

  if (!isSuccess) {
    return <div>Status: {status}...</div>;
  }

  return <div>{status}: {JSON.stringify(data)}</div>;
};

Using with Deno

import { fetchp } from "npm:fetchp";

const req = fetchp.request("GET", "https://www.google.com/");

console.log(await req.data);

Todo List

See GitHub Projects for more.

  • Clean cache storage
  • Fixing the bug in fetchp/mock module
  • Add advanced support for hooks / middlewares / interceptors
  • Protobuf support
  • Registering serializers / deserializers by content-type
  • Logging adapters
  • MAYBE: Reducers / Actions?
  • Mechanism for request retries

Requirements

License

Apache 2.0, for further details, please see LICENSE file

Contributing

See contributors.md

It is publicly open for any contribution. Bugfixes, new features and extra modules are welcome.

  • To contribute to code: Fork the repo, push your changes to your fork, and submit a pull request.
  • To report a bug: If something does not work, please report it using GitHub Issues.

To Support

Visit my GitHub Sponsors profile at github.com/sponsors/eserozvataf

More Repositories

1

hayalet-sevgilim-sarki-sozleri

Brainfuck
555
star
2

laroux.js

[Deprecated] Micro jquery substitute for modern browsers
JavaScript
422
star
3

acikkaynak-arsiv

açık-kaynak.org | İnisiyatif, Topluluk ve Rehber
369
star
4

developer-networks

Yazılımcı Telegram Topluluk ve Kanalları
143
star
5

acikkaynak-website

acik-kaynak.org 1.0
TypeScript
111
star
6

design-patterns

Design Patterns implemented in JavaScript/TypeScript
TypeScript
93
star
7

kontra-is-anlasmasi

86
star
8

stack

The Portability Solution for Your Code! 🚀 Powered By Deno and JavaScript.
TypeScript
76
star
9

evangelist

[Deprecated] 🌟 Library of helpers that are useful for functional programming
TypeScript
59
star
10

vscode-one-dark-pro-monokai-darker

A Darker One Dark Pro variation with Monokai scheme
58
star
11

hex-service

✖️ Deno and Node.js boilerplate for plain backend microservices
TypeScript
57
star
12

sey

[Deprecated] Simple JavaScript build tool with declarative and easy configuration
JavaScript
49
star
13

darty-react-app

[Deprecated] 🎯 React App Template For Darty Development Environment
TypeScript
46
star
14

acikseminer-demo

43
star
15

buildless-deno-react-ssr

"Buildless" starter project for React w/ SSR runs on Deno
JavaScript
42
star
16

aya-website

açık yazılım ağı web sitesi kaynak kodları
TypeScript
35
star
17

aspava

JavaScript
31
star
18

servicemanager

[Deprecated] 🔌 Most basic implementation of dependency injection container for JavaScript
TypeScript
29
star
19

immunity

[Deprecated] 🧱 Library of methods for maintaining immutable data structures
TypeScript
27
star
20

ne-lazim-abime

a utility-first, modern and progressive CSS framework by Eser Ozvataf
26
star
21

golang-service-template

Go
26
star
22

temporal-parse

parses human-readable strings for JavaScript's Temporal API
TypeScript
25
star
23

create-darty-app

[Deprecated] 🎯 Create Darty App
JavaScript
24
star
24

acikkaynak-api

JavaScript
20
star
25

festjs

the progressive javascript web framework by Eser Ozvataf
JavaScript
18
star
26

webend-demo

JavaScript
18
star
27

eser-npm

JavaScript Style Guide
JavaScript
18
star
28

react-eventmanager

[Deprecated] Event-based simple React state management with decorators
TypeScript
18
star
29

next-showcase

a project is designed to demonstrate the brand-new features of Next 15 and React 19
TypeScript
16
star
30

tassle

🧩 Bunch of .NET Standard Components designed to be parts of a well-functioning system
C#
16
star
31

apibone

[Deprecated] Abstracts requests and responses to make them platform agnostic
JavaScript
14
star
32

scabbia1

[Deprecated] Scabbia PHP Framework (1.x branch)
JavaScript
14
star
33

darty

[Deprecated] 🎯 Darty Development Environment
JavaScript
13
star
34

scabbia2-fw

Scabbia2 PHP Framework (will be broken a while)
PHP
12
star
35

tr2utf8

Simple tool to convert turkish-encoded files into utf-8 encoded ones
JavaScript
12
star
36

projeler

eser.live Projeleri
12
star
37

10fwd-website

TypeScript
9
star
38

eser.ozvataf.com

https://eser.ozvataf.com/
JavaScript
9
star
39

pm

A basic project management tool
JavaScript
8
star
40

scabbia2

Scabbia2 PHP Components
8
star
41

serverless-php

PHPKonf 2019 Konferansında sunacak olduğum "Serverless PHP" konuşmasının demo sunumudur
PHP
8
star
42

eser

7
star
43

DesktopTracker

C#
6
star
44

acikkaynak-webclient

JavaScript
6
star
45

acikkaynak-service

Python
6
star
46

hex-api-server

[Deprecated] An express wrapper with convention over configuration structure
JavaScript
6
star
47

hex-platform

An infrastructure bundle enables functions-as-a-service execution on your newly created or existing kubernetes cluster
HCL
6
star
48

kubernext

offering modern structure for every software team
Go
6
star
49

scabbia2-router

Scabbia2 Router Component
PHP
5
star
50

scabbia2-yaml

Scabbia2 Yaml Component
PHP
5
star
51

ponyfills

[Deprecated] 🦄 Delivers ponyfills as modules, uses native alternatives first when available
TypeScript
5
star
52

enthusiast

[Deprecated] 🎼 A functional stream library implementation runs on browsers and node.js
JavaScript
5
star
53

WinPhoneTetris

Tetris for Windows Phone 8 with XAML and Silverlight
C#
4
star
54

sqlsync

PHP
4
star
55

acikkaynak-website-old

TypeScript
4
star
56

leaves

JavaScript
4
star
57

jseditor

[Deprecated]
JavaScript
4
star
58

scabbia2-lightstack

Scabbia2 LightStack Component
PHP
4
star
59

deno-next-showcase

a project is designed to demonstrate the brand-new features of Deno 2, Next 15 and React 19
TypeScript
4
star
60

eserozvataf

3
star
61

personal-homepage

My personal homepage
JavaScript
3
star
62

acikkaynak.github.io

CSS
3
star
63

tassle-standards

3
star
64

vite-boilerplate

JavaScript
3
star
65

pullyn

One click to pull latest changes from repositories.
JavaScript
3
star
66

ssr-benchmark-deno

TypeScript
3
star
67

coollime

2
star
68

scabbia2-testing

Scabbia2 Testing Component
PHP
2
star
69

react-router-redux-example

JavaScript
2
star
70

opencast

TypeScript
2
star
71

scabbia2-services

Scabbia2 Services Component
PHP
2
star
72

scabbia2-helpers

Scabbia2 Helpers Component
PHP
2
star
73

jsmake

TypeScript
2
star
74

scabbia2-formatters

Scabbia2 Formatters Component
PHP
2
star
75

senior

[Deprecated] 🗃 Plugin host and manager for installable/removable npm packages
TypeScript
2
star
76

scabbia1-skeleton

[Deprecated] Skeleton Application for Scabbia PHP Framework (1.x branch)
PHP
2
star
77

jsmake-stack

[Deprecated] Deprecated in favor of hex
TypeScript
2
star
78

deno-boilerplate-console

Nothing fancy, just a simple boilerplate for Deno console apps
TypeScript
2
star
79

munakasa

JavaScript
2
star
80

eser.live

eser.live web site
TypeScript
2
star
81

scabbia2-tasks

Scabbia2 Tasks Component
PHP
1
star
82

scabbia2-scanners

Scabbia2 Scanners Component
PHP
1
star
83

denover

TypeScript
1
star
84

itec314

Solutions for the lab sessions of ITEC314 Multiplatform Programming (with Java) course.
1
star
85

XmlImport

PHP
1
star
86

scabbia2-config

Scabbia2 Config Component
PHP
1
star
87

survey

an online survey project using scabbia framework
PHP
1
star
88

BasketForm

A drag and drop file organizer
C#
1
star
89

cms

1
star
90

itec316

A kindergarten project for ITEC316 Software Engineering course
C#
1
star
91

entrepreneur

[Deprecated] JavaScript scaffolding tool on top of JSMake
JavaScript
1
star
92

istanbul-coders-deno-workshop

TypeScript
1
star
93

GeoRestriction

GeoRestriction Module for IonizeCMS
PHP
1
star
94

reports

Reports written by me, mostly for academic purposes
1
star
95

tsc-file-extension-problem

TypeScript
1
star
96

protokol.dev

1
star
97

jest-playground

JavaScript
1
star
98

eserozvataf.github.io

My github page
HTML
1
star
99

cmpe534

CMPE534 Automated Deduction Course
C#
1
star
100

maester

[Deprecated] 📜 Async logging and exception handling library runs on browsers and node.js
TypeScript
1
star