# @joseaburt/http-utils

> This is a package to abstract all boilerplate configurations for a production http client library. Axios is used as base provider.

Latest version **0.1.5** (published 2024-02-08) · MIT license · 0 weekly downloads

## Install

```sh
npm install @joseaburt/http-utils
pnpm add @joseaburt/http-utils
yarn add @joseaburt/http-utils
bun add @joseaburt/http-utils
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.1.5 |
| Published | 2024-02-08 |
| First published | 2023-10-25 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=12 |
| Dependencies | 0 |
| Unpacked size | 222 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Jose Aburto |
| Maintainers | jose_aburto |
| Keywords | axios, http, utils, rest, abortable, http-error |

## Links

- npm: https://www.npmjs.com/package/@joseaburt/http-utils
- Repository: https://github.com/joseaburt/http-utils
- Homepage: https://github.com/joseaburt/http-utils#readme
- Issues: https://github.com/joseaburt/http-utils/issues
- npm.io page: https://npm.io/package/@joseaburt/http-utils

## Alternatives

- [launchdarkly-js-client-sdk](https://npm.io/package/launchdarkly-js-client-sdk.md) — 2.5M weekly downloads
- [@elastic/elasticsearch](https://npm.io/package/@elastic/elasticsearch.md) — 2.1M weekly downloads
- [@c8y/client](https://npm.io/package/@c8y/client.md) — 15.3K weekly downloads
- [@signaldb/maverickjs](https://npm.io/package/@signaldb/maverickjs.md) — 1.7K weekly downloads
- [@bbc/http-transport-cache](https://npm.io/package/@bbc/http-transport-cache.md) — 1.2K weekly downloads

## Recent versions

- 0.1.5 (latest) — 2024-02-08
- 0.1.4 — 2024-01-19
- 0.1.3 — 2023-10-25
- 0.1.2 — 2023-10-25
- 0.1.1 — 2023-10-25
- 0.1.0 — 2023-10-25

## README

# http-utils

This is a package to abstract all boilerplate configurations for a production http client library. Axios is used as base provider

## Configuration / Initialization

```ts
import { HttpClient } from '.';
export const Http = HttpClient.getOrCreateInstance<'LEGACY_API' | 'ANOTHER_API' | 'PUBLIC'>();

Http.register('LEGACY_API', {
  baseURL: 'http://legacy.company.com/api/v1',
  getToken: () return localStorage.getItem('token') ?? "",
  beforeRedirect(options, responseDetails) {
    console.log(options, responseDetails);
  },
  onSessionExpired(error) {
    console.log(error);
  },
  onUnauthorized(error) {
    console.log(error);
  },
});

Http.register('ANOTHER_API', {
  baseURL: 'http://another.company.com/api/v1',
  getToken: () return process.env.ACCESS_TOKEN ?? "",
  beforeRedirect(options, responseDetails) {
    console.log(options, responseDetails);
  },
  onSessionExpired(error) {
    console.log(error);
  },
  onUnauthorized(error) {
    console.log(error);
  },
});
```

## Basic Usage

```TypeScript
Http.getInstance('ANOTHER_API')
  .get('/customers')
  .then(console.log)
  .catch((err) => console.log(HttpClient.parseError(err)));
```

## Using Http Methods

| Method             | Description                                                             |
| ------------------ | ----------------------------------------------------------------------- |
| GetMethod          | Retrieves data from a specified resource.                               |
| PostMethod         | Submits data to be processed to a specified resource.                   |
| PatchMethod        | Partially updates data on a specified resource.                         |
| PutMethod          | Updates a resource or creates it if it doesn't exist.                   |
| DeleteMethod       | Removes data from a specified resource.                                 |
| DownloadFileMethod | Downloads a file from a specified resource. The progress is trackeable. |
| UploadFileMethod   | Uploads a file to a specified resource. The progress is trackeable.     |

### Declarative way

```ts
import { GetMethod } from '.';

GetMethod.build(Http.getInstance('ANOTHER_API'))
  .send('/customers')
  .then(console.log)
  .catch((err) => console.log(HttpClient.parseError(err)));
```

#### Abort Calls

```ts
import { GetMethod } from '.';

const instance = GetMethod.build(Http.getInstance('ANOTHER_API'));

instance
  .send('/customers')
  .then(console.log)
  .catch((err) => console.log(HttpClient.parseError(err)));

instance.abort();
```

### Imperative way

```ts
import { PostMethod } from '.';

type LogicResponse = {};
type BasicCredentials = { email: string; password: string };

class LoginUseCase extends PostMethod<BasicCredentials, BackendResponse<LogicResponse>> {
  constructor(instance: AxiosInstance) {
    super(instance);
  }
  public async execute(credentials: BasicCredentials): Promise<void> {
    Assert.assertBasicCredentials(credentials);
    const { data: userSession } = await this.send('/customers', credentials);

    DomainStorage.persistSession(userSession);
    DomainBus.dispatch(DomainEvents.SessionSuccess, userSession);
  }
}
```

## DownloadFileMethod

Here an example of how to use it. In this example I am creating a hoc that will create a downloadable generic component.

```ts
import { DownloadFileMethod } from '.';

const instance = DownloadFileMethod.build(Http.getInstance('ANOTHER_API'));

type ProgressState = { progress: number; loading: boolean; error?: string };
type DownloadComponentProps = { onClick(): void; progress: ProgressState };

function createDownloadComponent(Component: ComponentType<DownloadComponentProps>): ComponentType<Props> {
  return function DownloadComponent({ src, children }: Props): JSX.Element {
    const [progress, setProgress] = useState<ProgressState>({ loading: false, progress: 0 });

    useEffect(() => {
      instance.subscribeToProgress(({ progress }) => setProgress((pre) => ({ ...pre, progress })));
      return () => instance.abort();
    }, []);

    const handleOnClick = () => {
      setProgress((pre) => ({ ...pre, loading: true }));
      instance
        .send(src)
        .then((response) => MediaUtils.download(response.data))
        .catch((error) => setProgress((pre) => ({ ...pre, error: HttpClient.parseError(error).message })))
        .finally(() => setProgress((pre) => ({ ...pre, loading: false })));
    };

    return (
      <Component onClick={handleOnClick} progress={progress}>
        {children}
      </Component>
    );
  };
}
```

## UploadFileMethod

`UploadFileMethod` is similar than `DownloadFileMethod`, both extend from the same base class `ProgressiveFileMethod`. So use it like the same.

### Similarities and Differences

```ts
// DownloadFileMethod
abort(): void
send(endpoint: string): Promise<AxiosResponse<Blob>> // 👈🏼 Check this
subscribeToProgress(subscriber: ProgressSubscriber)

// UploadFileMethod
abort(): void
send(endpoint: string, formData: FormData): Promise<AxiosResponse<T>> // 👈🏼 The difference is here, we need the `FormData` payload for uploading.
subscribeToProgress(subscriber: ProgressSubscriber)
```

## Error Handling

The `HttpClient` class has an static method called `parseError` for parsing errors from http calls.

```ts
(async function () {
  try {
    await Http.getInstance('ANOTHER_API').get('/customers');
  } catch (error) {
    const { code, status, message, context } = HttpClient.parseError(normalError);
    // Frontend side Example
    Application.showToast('error', message);
  }
})();
```

---
_Source: https://npm.io/package/@joseaburt/http-utils · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
