shelving
Version:
Toolkit for using data in JavaScript.
41 lines (40 loc) • 1.97 kB
JavaScript
import { debugRequest } from "../../util/debug.js";
import { ClientAPIProvider } from "./ClientAPIProvider.js";
import { ThroughAPIProvider } from "./ThroughAPIProvider.js";
/** Default handler just echoes back the input request as text. */
async function _mockHandler(request) {
return new Response(`Mocked response to ${debugRequest(request)}`, { status: 200, statusText: "OK" });
}
/**
* Provider that logs API calls without sending network requests.
* - Extends `ThroughAPIProvider` to delegate request building and response parsing to a source `APIProvider`.
* - The source provider's `fetch()` is never called — this provider intercepts all fetches and routes them through a `RequestHandler`.
*/
export class MockAPIProvider extends ThroughAPIProvider {
requestCalls = [];
fetchCalls = [];
responseCalls = [];
handler;
constructor(handler = _mockHandler, source = new ClientAPIProvider({ url: "https://api.mock.com" })) {
super(source);
this.handler = handler;
}
// Override `createRequest()` to log the endpoint and payload before delegating to the source provider for request building.
createRequest(endpoint, payload, options, caller = this.createRequest) {
const request = super.createRequest(endpoint, payload, options, caller);
this.requestCalls.push({ endpoint, payload, options, request });
return request;
}
// Override `parseResponse()` to log the response and result.
async parseResponse(endpoint, response, caller = this.parseResponse) {
const result = await super.parseResponse(endpoint, response, caller);
this.responseCalls.push({ endpoint, response, result });
return result;
}
// Override `fetch()` to route through the handler instead of the network.
async fetch(request) {
const response = await this.handler(request);
this.fetchCalls.push({ request, response });
return response;
}
}