Repository pattern implementation with a tiny HttpClient based on Fetch API.
npm install @volverjs/data
repository http-client url-builder fetch
    
maintained with ❤️ by

``bashpnpm
pnpm add @volverjs/data
Usage
This library exports four main classes:
Hash, UrlBuilder, HttpClient and RepositoryHttp.`typescript
import { Hash, HttpClient, RepositoryHttp, UrlBuilder } from '@volverjs/data'
`$3
The
Hash class provides some static functions to generate hashes.`typescript
import { Hash } from '@volverjs/data'const hash = Hash.cyrb53('hello world')
`$3
The
UrlBuilder class provides a way to build URLs with template parameters and query string.`typescript
import { UrlBuilder } from '@volverjs/data'const urlBuilder = new UrlBuilder({
encodeValuesOnly: false
})
const url = urlBuilder.build('https://my.api.com/:endpoint', {
endpoint: 'users',
_limit: 10,
_page: 1
})
// url = 'https://my.api.com/users?_limit=10&_page=1'
`Instead of
URLSearchParams, the query parameters are automatically encoded using qs library.
Please refer to the UrlBuilder docs for more informations.$3
The
HttpClient class is a wrapper around ky, a client based on fetch API . It provides a simple interface to make HTTP requests and uses UrlBuilder to build URLs.`typescript
import { HttpClient } from '@volverjs/data'const client = new HttpClient({
prefixUrl: 'https://my.api.com'
})
const response = await client.get({
template: ':endpoint/:action?/:id',
params: {
endpoint: 'users',
id: 1,
_limit: 10,
_page: 1
}
})
// fetch('https://my.api.com/users/1?_limit=10&_page=1', { method: 'GET' })
`Please refer to the
HttpClient docs for more informations.$3
The
RepositoryHttp class is an implementation of the Repository interface for http requests using HttpClient. It was designed with the repository pattern in mind to provide a simple way to make CRUD operations on a REST API.`typescript
import { HttpClient, RepositoryHttp } from '@volverjs/data'class User {
id: number
name: string
surname: string
constructor(data: { id: number, name: string, surname: string }) {
this.id = data.id
this.name = data.name
this.email = data.email
}
get fullName() {
return
${this.name} ${this.surname}
}
}const client = new HttpClient({
prefixUrl: 'https://my.api.com'
})
const repository = new RepositoryHttp(client, 'users/:group?/:id?', {
class: User
})
const getAdminUsers: User[] = async () => {
const { responsePromise } = repository.read({
group: 'admin'
})
const { data } = await responsePromise
return data
}
`Please refer to the
RepositoryHttp docs for more informations.Vue
You can use this library with Vue 3 with
@volverjs/data/vue.$3
The
createHttpClient function returns a plugin that can be installed in a Vue app and has a property with the global httpClient instance: httpClientPlugin.globalInstance.`typescript
import { createHttpClient } from '@volverjs/data/vue'
import { createApp } from 'vue'
import App from './App.vue'const app = createApp(App)
const httpClientPlugin = createHttpClient({
prefixUrl: 'https://my.api.com'
})
app.use(httpClientPlugin, {
globalName: 'vvHttp' // (optional) default: 'vvHttp'
})
`With
app.use(httpClientPlugin) the HttpClient instance will be available in all components as $vvHttp with Options API.
Use globalName to change the name vvHttp.$3
Alternatively, you can use the
useHttpClient() and useRepositoryHttp() composables to get the HttpClient instance in a specific component.####
useHttpClient()If
HttpClientPlugin is not created with createHttpClient() or the httpClient scope requested not exist (ex: useHttpClient('instanceNotExist')), then useHttpClient() throw the error HttpClient instance not found.`vue
Loading...
{{ error }}
{{ data?.[0].name }}
`useHttpClient() also exposes request(), requestGet(), requestPost(), requestPut(), requestPatch() and requestDelete() methods. These methods are wrappers around the HttpClient methods with reactivity.`vue
Loading...
{{ error }}
{{ data.name }}
`Each method returns an object with the following properties:
-
isLoading: a computed that indicates if the request is loading;
- isError: a computed that indicates if the request has failed;
- isSuccess: a computed that indicates if the request has succeeded;
- error: a readonly ref that contains the error message;
- response: a ref that contains the response;
- data: a ref that contains the response data (.json() function);
- execute(): a function that executes the request.The request can be executed later by setting the
immediate option to false (default: true).`vue
`The
execute() function returns an object with the following properties:-
responsePromise: a Promise that resolves with the response;
- abort: a function that aborts the request;
- signal: an AbortSignal that can be used to check if the request has been aborted.####
useRepositoryHttp()To create a
RepositoryHttp instance, you can use the useRepositoryHttp() composable.##### Parameters
-
template: string | HttpClientUrlTemplate,
- options?: RepositoryHttpOptions##### Example 1
`vue
Loading...
{{ error }}
{{ item.name }}
`##### Example 2 - Typing server response for
responseAdapter`vue
Loading...
{{ error }}
{{ data.name }}
`useRepositoryHttp() also exposes create(), read(), update() and remove() methods. These methods are wrappers around the RepositoryHttp methods with reactivity.`vue
Loading...
{{ error }}
{{ item.name }}
`Each method returns an object with the following properties:
-
isLoading: a computed that indicates if the request is loading;
- isSuccess: a computed that indicates if the request has succeeded;
- isError: a computed that indicates if the request has failed;
- error: a readonly ref that contains the error message;
- execute(): a function that executes the request.create(), read(), update() also return:-
data a ref that contains the response data;
- metadata a ref that contains the response metadata;read() also returns:-
item a ref that contains the first item of the response data;The request can be executed later by setting the
immediate option to false (default: true).`vue
`The
execute() function returns an object with the following properties:-
responsePromise: a Promise that resolves with the response;
- abort: a function that aborts the request;
- signal: an AbortSignal that can be used to check if the request has been aborted.Advanced usage
HttpClientPlugin manage most of use cases (ex: micro-frontend with different httpClient, a SPA with authenticated API calls and public API calls, etc..).
The HttpClientPlugin can manage a Map of httpClient instances.$3
With
scope parameter on createHttpClient() multiple httpClient instances can be created. If the httpClient scope instance already exist an error is throwed: httpClient with scope ${scope} already exist.##### Parameters:
options?: HttpClientInstanceOptions & { scope: string }##### Example:
`vue
`$3
With this composable the
httpClient instance can be removed from Map instances.
The global httpClient instance cannot be removed.##### Parameters:
scope: string,##### Example:
`vue
`Note: The
httpClient Map instances is NOT reactive, so after the removeHttpClient, the httpClient used before will NOT be destroyed.Acknoledgements
The
UrlBuilder class is inspired by urlcat`.