@rxliuli/vista is a powerful homogeneous request interceptor library that supports unified interception of Fetch/XHR requests. It allows you to intervene at different stages of the request lifecycle, enabling various functions such as request monitoring, modification, and mocking.
npm install @rxliuli/vista # Or yarn add @rxliuli/vista # Or pnpm add @rxliuli/vista
import { Vista } from '@rxliuli/vista' new Vista() .use(async (c, next) => { console.log('Request started:', c.req.url) await next() }) .use(async (c, next) => { await next() console.log('Response data:', await c.res.clone().text()) }) .intercept()
new Vista() .use(async (c, next) => { c.req.headers.set('Authorization', 'Bearer token') await next() }) .intercept()
const cache = new Map() new Vista() .use(async (c, next) => { const key = c.req.url if (cache.has(key)) { c.res = cache.get(key).clone() return } await next() cache.set(key, c.res.clone()) }) .intercept()
new Vista() .use(async (c, next) => { const maxRetries = 3 let retries = 0 while (retries < maxRetries) { try { await next() break } catch (err) { retries++ if (retries === maxRetries) throw err } } }) .intercept()
new Vista() .use(async (c, next) => { await next() if (c.req.url === 'https://example.com/example') { const json = await c.res.json() json.id = 2 c.res = new Response(JSON.stringify(json), c.res) } }) .intercept()
Main interceptor class, providing the following methods:
The middleware function receives two parameters:
const vista = new Vista() vista.intercept() // When not needed vista.destroy()
Does it support asynchronous operations?
Yes, the middleware supports async/await syntax.
Does it support intercepting requests in Node.js?
No, it only supports intercepting requests in the browser.
Welcome to submit Issues and Pull Requests!
MIT License
Try it and tell me your experience, welcome any error or feature feedback.
The above is the detailed content of Introduction to @rxliuli/vista: A unified request interceptor library for both Fetch and XHR with middleware support.. For more information, please follow other related articles on the PHP Chinese website!