Skip to content

Commit

Permalink
Merge pull request #30 from distributed-lab/feature/fetcher-standalone
Browse files Browse the repository at this point in the history
Feature/fetcher standalone
  • Loading branch information
napalmpapalam authored Jun 28, 2023
2 parents 7e46e0a + b5b0297 commit 2c62703
Show file tree
Hide file tree
Showing 15 changed files with 169 additions and 26 deletions.
4 changes: 2 additions & 2 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
tab_width = 2

[*.md]
max_line_length = 0
trim_trailing_whitespace = true
max_line_length = 100
12 changes: 10 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.2.0-rc.20] - 2023-06-28
### Added
- `@distributedlab/fetcher` - `fetcher` standalone instance

### Fixed
- `@distributedlab/w3p` - Circular dependency

## [0.2.0-rc.19] - 2023-06-09
- `@distributedlab/reactivity` - `extend` hook return type
- `@distributedlab/reactivity` - `ref` hook value argument type
Expand Down Expand Up @@ -231,14 +238,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `root`: `yarn rsc` Release Sanity Check script
- `root`: Rollup and configuration file to build packages for CDN
- `@distributedlab/tools`: Handling big numbers
- `@distributedlab/tools`: Add tests for time.ts and duration.ts
- `@distributedlab/tools`: Add tests for time.ts and duration.ts

### Changed****
- `root`: Updated `README.md`

[old repo]: https://github.com/distributed-lab/web-kit-old

[Unreleased]: https://github.com/distributed-lab/web-kit/compare/0.2.0-rc.19...HEAD
[Unreleased]: https://github.com/distributed-lab/web-kit/compare/0.2.0-rc.20...HEAD
[0.2.0-rc.20]: https://github.com/distributed-lab/web-kit/compare/0.2.0-rc.19...0.2.0-rc.20
[0.2.0-rc.19]: https://github.com/distributed-lab/web-kit/compare/0.2.0-rc.18...0.2.0-rc.19
[0.2.0-rc.18]: https://github.com/distributed-lab/web-kit/compare/0.2.0-rc.17...0.2.0-rc.18
[0.2.0-rc.17]: https://github.com/distributed-lab/web-kit/compare/0.2.0-rc.16...0.2.0-rc.17
Expand Down
47 changes: 35 additions & 12 deletions packages/fetcher/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# @distributedlab/fetcher

Fetch API wrapper with the extended functionality and simple interface.

![version (scoped package)](https://badgen.net/npm/v/@distributedlab/fetcher)
Expand All @@ -21,15 +22,18 @@ import { Fetcher } from '@distributedlab/fetcher'
```

CommonJS:

```ts
const { Fetcher } = require('@distributedlab/fetcher')
```

Via CDN:

In HTML:

```html
<script src="https://unpkg.com/@distributedlab/fetcher"></script>

<script src='https://unpkg.com/@distributedlab/fetcher'></script>
```

In code:
Expand Down Expand Up @@ -94,18 +98,19 @@ const api = new Fetcher({

const getDataWithQuery = async () => {
const { data } = await api.get<{ name: string }>('/data', {
query: {
filter: "John",
query: {
filter: "John",
exists: true,
"page[number]": 1,
include: ["comments", "posts"],
}
})
}
})
return data
}
```

`POST` request (`PUT`, `PATCH` request has pretty much the same interface, just use `put` or `patch` method instead of `post`):
`POST` request (`PUT`, `PATCH` request has pretty much the same interface, just use `put` or `patch`
method instead of `post`):

```ts
import { Fetcher } from '@distributedlab/fetcher'
Expand All @@ -116,10 +121,10 @@ const api = new Fetcher({

const postData = async () => {
const { data } = await api.post<{ name: string }>('/data', {
body: {
name: "John",
}
})
body: {
name: "John",
}
})
return data
}
```
Expand Down Expand Up @@ -180,7 +185,7 @@ const api = new Fetcher({
api.addInterceptor({
request: async request => {
// Do something before request is sent
return {...request, url: `${request.url}?foo=bar`}
return { ...request, url: `${request.url}?foo=bar` }
},
response: async response => {
// Do something with response
Expand All @@ -202,6 +207,24 @@ api.addInterceptor({

```

### Standalone

The `Fetcher` standalone feature offers the convenience of making requests to an external API without
the need to create an instance or configure options such as `baseUrl`. It proves particularly useful
in scenarios where you require a one-time request and prefers to avoid the overhead of setting up a
`Fetcher` instance:

```ts
import { fetcher } from '@distributedlab/fetcher'

const getData = async () => {
const { data } = await fetcher.get<{ name: string }>('https://api.example.com/data')
console.log(data) // { name: 'John' }
}
```

## Changelog

For the change log, see [CHANGELOG.md](https://github.com/distributed-lab/web-kit/blob/main/CHANGELOG.md).
For the change log, see [CHANGELOG.md].

[CHANGELOG.md]: https://github.com/distributed-lab/web-kit/blob/main/CHANGELOG.md
2 changes: 1 addition & 1 deletion packages/fetcher/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@distributedlab/fetcher",
"version": "0.2.0-rc.19",
"version": "0.2.0-rc.20",
"description": "Fetch API wrapper with the extended functionality and simple interface",
"repository": {
"type": "git",
Expand Down
4 changes: 2 additions & 2 deletions packages/fetcher/src/const/config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { FetcherConfig } from '@/types'

export const DEFAULT_CONFIG: Omit<FetcherConfig, 'baseUrl'> = {
credentials: 'include',
credentials: 'omit',
cache: 'no-store',
referrerPolicy: 'strict-origin-when-cross-origin',
referrerPolicy: 'no-referrer',
mode: 'cors',
timeout: 60000,
}
8 changes: 8 additions & 0 deletions packages/fetcher/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,11 @@ export class FetcherError<T = undefined> extends Error {
this.request = resp.request
}
}

export class FetcherURLParseError extends Error {
public name = 'FetcherURLParseError'

constructor(e = new TypeError('Failed to parse URL')) {
super(e.toString())
}
}
100 changes: 100 additions & 0 deletions packages/fetcher/src/fether-standalone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { HTTP_METHODS } from '@/enums'
import { FetcherURLParseError } from '@/error'
import { Fetcher } from '@/fetcher'
import type {
FetcherRequestOpts,
FetcherResponse,
FetcherStandaloneConfig,
} from '@/types'

const parseUrl = (u: string): URL => {
try {
return new URL(u)
} catch (e) {
throw new FetcherURLParseError(e as Error)
}
}

const performRequest = async <T>(
u: URL,
method: HTTP_METHODS,
cfg: FetcherStandaloneConfig,
opts?: FetcherRequestOpts,
reqCfg?: FetcherStandaloneConfig,
): Promise<FetcherResponse<T>> => {
return new Fetcher({
...cfg,
...(reqCfg ? reqCfg : {}),
baseUrl: u.origin,
}).request<T>({
endpoint: u.pathname,
method,
...(opts || {}),
})
}

export const fetcher = {
config: {} as FetcherStandaloneConfig,

setConfig(cfg: FetcherStandaloneConfig): void {
this.config = { ...this.config, ...cfg }
},

get<T>(
u: string,
opts?: FetcherRequestOpts,
cfg?: FetcherStandaloneConfig,
): Promise<FetcherResponse<T>> {
return performRequest(parseUrl(u), HTTP_METHODS.GET, this.config, opts, cfg)
},

post<T>(
u: string,
opts?: FetcherRequestOpts,
cfg?: FetcherStandaloneConfig,
): Promise<FetcherResponse<T>> {
return performRequest(
parseUrl(u),
HTTP_METHODS.POST,
this.config,
opts,
cfg,
)
},

patch<T>(
u: string,
opts?: FetcherRequestOpts,
cfg?: FetcherStandaloneConfig,
): Promise<FetcherResponse<T>> {
return performRequest(
parseUrl(u),
HTTP_METHODS.PATCH,
this.config,
opts,
cfg,
)
},

put<T>(
u: string,
opts?: FetcherRequestOpts,
cfg?: FetcherStandaloneConfig,
): Promise<FetcherResponse<T>> {
return performRequest(parseUrl(u), HTTP_METHODS.PUT, this.config, opts, cfg)
},

delete<T>(
u: string,
opts?: FetcherRequestOpts,
cfg?: FetcherStandaloneConfig,
): Promise<FetcherResponse<T>> {
return performRequest(
parseUrl(u),
HTTP_METHODS.DELETE,
this.config,
opts,
cfg,
)
},
}
4 changes: 2 additions & 2 deletions packages/fetcher/src/helpers/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ const ABORT_MANAGER = {
const RESULT = {
body: null,
cache: 'no-store',
credentials: 'include',
credentials: 'omit',
method: 'GET',
referrerPolicy: 'strict-origin-when-cross-origin',
referrerPolicy: 'no-referrer',
signal: ABORT_MANAGER.setSafe(REQUEST_CFG.id),
headers: {
'Content-Type': 'application/json',
Expand Down
1 change: 1 addition & 0 deletions packages/fetcher/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ export * from './const'
export * from './enums'
export * from './error'
export * from './fetcher'
export * from './fether-standalone'
export * from './interceptor-manager'
export * from './types'
2 changes: 2 additions & 0 deletions packages/fetcher/src/types/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,5 @@ export type FetcherResponse<T> = {
request: FetcherRequest
data?: T
}

export type FetcherStandaloneConfig = Omit<FetcherConfig, 'baseUrl'>
2 changes: 1 addition & 1 deletion packages/jac/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@distributedlab/jac",
"version": "0.2.0-rc.19",
"version": "0.2.0-rc.20",
"description": "A library for constructing JSON-API compliant requests and responses",
"repository": {
"type": "git",
Expand Down
2 changes: 1 addition & 1 deletion packages/reactivity/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@distributedlab/reactivity",
"version": "0.2.0-rc.19",
"version": "0.2.0-rc.20",
"description": "Implementation of the reactivity connections to propagate changes between objects",
"repository": {
"type": "git",
Expand Down
2 changes: 1 addition & 1 deletion packages/tools/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@distributedlab/tools",
"version": "0.2.0-rc.19",
"version": "0.2.0-rc.20",
"description": "Collection of common utility functions and classes",
"repository": {
"type": "git",
Expand Down
2 changes: 1 addition & 1 deletion packages/w3p/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@distributedlab/w3p",
"version": "0.2.0-rc.19",
"version": "0.2.0-rc.20",
"description": "Wrapper for Web3 Providers",
"repository": {
"type": "git",
Expand Down
3 changes: 2 additions & 1 deletion packages/w3p/src/providers/wrapped/fallback-evm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
getEthExplorerTxUrl,
hexToDecimal,
} from '@/helpers'
import { ProviderEventBus } from '@/providers'
import type {
Chain,
ChainId,
Expand All @@ -17,6 +16,8 @@ import type {
TransactionResponse,
} from '@/types'

import { ProviderEventBus } from '../wrapped/_event-bus'

export class FallbackEvmProvider
extends ProviderEventBus
implements ProviderProxy
Expand Down

0 comments on commit 2c62703

Please sign in to comment.