UBuilder REST API
npm install @ubuilder/restWARNING: UBuilder REST v8 is not compatible with version 7.
UBuilder REST internally uses Fetch API.
If target browser doen't support Fetch API, should add polyfill 'whatwg-fetch'.
npm i @ubuilder/rest
`Exports
`javascript
// named class export
export { Rest };
// plugin export for vue.js
export default {
install(app, options = {}) { / ... / }
};
`Usage
$3
`javascript
// on Vue 2
import Vue from 'vue';
import Rest from '@ubuilder/rest';Vue.use(Rest, { baseURL: '/' });
// on Vue 3
import { createApp } from 'vue';
import Rest from '@ubuilder/rest';
const app = createApp(/ app options /);
app.use(Rest, { baseURL: '/' });
`$3
`typescript
// Vue 2 in methods
this.$rest.get('/').then((json) => { this.getData = json });// Vue 3 inject
const component = {
inject: {
rest: {
from: 'rest'
}
}
};
// Vue 3 setup inject
import { inject, ref } from 'vue';
import { Rest } from '@ubuilder/rest'; // Rest class, not default import
const getData = ref();
const rest = inject('rest'); // check providePrefix option
rest.get('/').then((json) => { getData.value = json });
`PluginOptions
* baseURL : url base, defaults to '/'.
* headers : default headers, defaults to {}.
* interceptors: array of interceptors.
* providePrefix : prefix for provide/inject. Default value is '' (empty string).Error Handling
* on network error, throws error from fetch API.
* on response is not ok (check by response.ok), throws RestError { status, response }.
!!! Do not rely on http error message. HTTP/2 does not have statusText. Must check by status. !!!Interceptors
Interceptors are chained. Interceptors called on request, response, error.
Global interceptors are removed on v8.`typescript
{
onRequest?: (options: Promise) => Promise
onResponse?: (response: Response) => Response
onError?: (error: Error) => boolean
}
`
* onRequest : fetch request options for manipulation. Should returns options promise. To stop processing, reject.
* onResponse : on fetch response. Should returns response.
* error: receive error, returns boolean. if returns true, that error is handled, chain stops and does not throws error.Example
`javascript
const json = await this.$rest.get('/url');this.$rest.post('/url', {});
``