Vue3 HTTP Client using RxJS
install using npm
npm install vee-http
import createApp from 'vue';
import App from 'vue/App';
import createVHttpClient from 'v-http';
const app = createApp(App)
app.use(createVHttpClient())
You can access the client via the registered globals
export default createComponent({
data() {
names: []
},
beforeMount() {
this.$vHttpClient.get('my.api-server.com/endpoint')
.subscribe(endpointData => this.name = endpointData)
}
})
const {http} = useVHttpClient();
updateItem(item: {id: string, value: string}) {
http.put('http://my-item.server./items/' + item.id, item, {
queryParams: {full: 'true'}
})
.pipe(
map(res => true),
catchError(e => {
if (e.status === 404) {
console.error(`item ${ id } does not exist!`);
return EMPTY;
}
})
)
.subscribe(res => console.log(`item ${ id } updated!`))
}
Interceptors are chained in the order that they are passed to the array. They're useful for global level settings, like authentication headers, caching and logging.
// you can use the interceptor to intercept responses
// by using the rxjs pipe operator
function loggerInterceptor(req, next) {
const start = performance.now();
return next(req)
.pipe(
tap(_ => console.log(`request executed in ${performance.now() - start}`))
);
}
// or you can use the interceptors to
// change the request
function authInterceptor(req, next) {
const updatedReq = {
...req,
headers: {
...req.headers,
'Authorization': 'Basic [token]'
}
};
return next(updatedReq);
}
const interceptors = [
loggerInterceptor,
authInterceptor,
]
app.use(createVHttpClient(interceptors))
All the calls can be converted to promises using the lastValueFrom (or firstValueFrom) operator.
The caveat here is that this has to be the first interceptor in the chain and the types have to be coerced into Promises.
import lastValueFrom from 'rxjs/operators';
async function loggerInterceptor(req, next): Promise<unknown> {
const start = performance.now();
const res = await lastValueFrom(next(req))
console.log(`request executed in ${performance.now() - start}`)
return res;
}
for more details please see the documentation
npm run build
If you wish to test the package locally use
npm run build:local
Library is under active development and may have API breaking changes for subsequent major versions after 1.0.0.
Generated using TypeDoc