### Install Wretch v2 Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V2_V3.md Instructions for installing Wretch v2 if needed, for example, to support older Node.js versions. ```bash npm install wretch@^2 ``` -------------------------------- ### Setup toolchain with proto Source: https://github.com/elbywan/wretch/blob/master/CONTRIBUTING.md Instructions for installing proto and setting up the project's tool versions. ```bash # macOS/Linux curl -fsSL https://moonrepo.dev/install/proto.sh | bash # Windows irm https://moonrepo.dev/install/proto.ps1 | iex ``` ```bash proto use ``` -------------------------------- ### Quick Start Example Source: https://github.com/elbywan/wretch/blob/master/docs/index.html Build beautiful, chainable HTTP requests in seconds. ```javascript import wretch from "wretch" wretch() .url("https://jsonplaceholder.typicode.com/users") .json({ name: "John Doe", email: "john@example.com" }) // .formData, .formUrl… .post() // .get, .put, .patch, .delete… .notFound(err => console.log("User not found")) // .unauthorized, .forbidden… .error(500, err => console.log("Server error")) ``` -------------------------------- ### Quick start example Source: https://github.com/elbywan/wretch/blob/master/README.md Quick start example showing basic wretch usage ```bash # 1️⃣ Install npm i wretch ``` ```javascript // 2️⃣ Import and create a reusable API client import wretch from "wretch" const api = wretch("https://jsonplaceholder.typicode.com") .options({ mode: "cors" }) // 3️⃣ Make requests with automatic JSON handling const post = await api.get("/posts/1").json() console.log(post.title) // 4️⃣ POST with automatic serialization const created = await api .post({ title: "New Post", body: "Content", userId: 1 }, "/posts") .json() // 5️⃣ Handle errors elegantly await api .get("/posts/999") .notFound(() => console.log("Post not found!")) .json() // 6️⃣ Different response types const text = await api.get("/posts/1").text() // Raw text const response = await api.get("/posts/1").res() // Raw Response object const blob = await api.get("/photos/1").blob() // Binary data ``` -------------------------------- ### Plugin Loading in Config Source: https://github.com/elbywan/wretch/blob/master/test/snippets/examples/README.md Example of how to load plugins via a configuration file. ```json { "plugins": [ "./path/to/my-plugin.js" ] } ``` -------------------------------- ### Addons System - Before (v1) Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V1_V2.md Example of using formData and query features directly in v1. ```javascript import wretch from "wretch" wretch() .formData({ hello: "world" }) .query({ check: true }) ``` -------------------------------- ### Addons System - After (v2) Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V1_V2.md Example of importing and registering addons for formData and query features in v2. ```javascript import FormDataAddon from "wretch/addons/formData" import QueryStringAddon from "wretch/addons/queryString" import wretch from "wretch" // Register addons const w = wretch().addon(FormDataAddon).addon(QueryStringAddon) // Now the features are available w.formData({ hello: "world" }).query({ check: true }) ``` -------------------------------- ### Browser Module Import Examples Source: https://github.com/elbywan/wretch/blob/master/README.md Browser module import examples ```typescript // ECMAScript modules import wretch from "wretch" // CommonJS const wretch = require("wretch") // Global variable (script tag) window.wretch ``` -------------------------------- ### Staying on v1 - Installation Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V1_V2.md Command to install Wretch v1 for environments requiring older compatibility. ```bash npm install wretch@^1 ``` -------------------------------- ### Advanced middleware examples Source: https://github.com/elbywan/wretch/blob/master/README.md Demonstrates various middleware implementations including delay, short-circuiting, logging, and caching, along with examples of how to use them individually or chained. ```javascript /* A simple delay middleware. */ const delayMiddleware = delay => next => (url, opts) => { return new Promise(res => setTimeout(() => res(next(url, opts)), delay)) } /* Returns the url and method without performing an actual request. */ const shortCircuitMiddleware = () => next => (url, opts) => { // We create a new Response object to comply because wretch expects that from fetch. const response = new Response(url) // Instead of calling next(), returning a Response Promise bypasses the rest of the chain. return Promise.resolve(response) } /* Logs all requests passing through. */ const logMiddleware = () => next => (url, opts) => { console.log(opts.method + "@" + url) return next(url, opts) } /* A throttling cache. */ const cacheMiddleware = (throttle = 0) => { const cache = new Map() const inflight = new Map() const throttling = new Set() return next => (url, opts) => { const key = opts.method + "@" + url if(!opts.noCache && throttling.has(key)) { // If the cache contains a previous response and we are throttling, serve it and bypass the chain. if(cache.has(key)) return Promise.resolve(cache.get(key).clone()) // If the request in already in-flight, wait until it is resolved else if(inflight.has(key)) { return new Promise((resolve, reject) => { inflight.get(key).push([resolve, reject]) }) } } // Init. the pending promises Map if(!inflight.has(key)) inflight.set(key, []) // If we are not throttling, activate the throttle for X milliseconds if(throttle && !throttling.has(key)) { throttling.add(key) setTimeout(() => { throttling.delete(key) }, throttle) } // We call the next middleware in the chain. return next(url, opts) .then(_ => { // Add a cloned response to the cache cache.set(key, _.clone()) // Resolve pending promises inflight.get(key)?.forEach((([resolve, reject]) => resolve(_.clone()))) // Remove the inflight pending promises inflight.delete(key) // Return the original response return _ }) .catch(_ => { // Reject pending promises on error inflight.get(key)?.forEach(([resolve, reject]) => reject(_)) inflight.delete(key) throw _ }) } } // To call a single middleware const cache = cacheMiddleware(1000) wretch("https://httpbingo.org/get").middlewares([cache]).get() // To chain middlewares wretch("https://httpbingo.org/get").middlewares([ logMiddleware(), delayMiddleware(1000), shortCircuitMiddleware() ]).get().text(text => console.log(text)) // To test the cache middleware more thoroughly const wretchCache = wretch("https://httpbingo.org").middlewares([cacheMiddleware(500)]) const printResource = (url, timeout = 0) => { return new Promise(resolve => setTimeout(async () => { wretchCache.url(url).get().notFound(console.error).text(resource => { console.log(resource) resolve(resource) }) }, timeout)) } // The resource url, change it to an invalid route to check the error handling const resourceUrl = "/base64/decode/YWVhY2YyYWYtODhlNi00ZjgxLWEwYjAtNzdhMTIxNTA0Y2E4" // Only two actual requests are made here even though there are 30 calls await Promise.all(Array.from({ length: 10 }).flatMap(() => [ printResource(resourceUrl), printResource(resourceUrl, 200), printResource(resourceUrl, 700) ] )) ``` -------------------------------- ### Basic Deno usage example Source: https://github.com/elbywan/wretch/blob/master/README.md A simple example demonstrating how to use Wretch in a Deno environment. ```ts import wretch from "wretch"; const text = await wretch("https://httpbingo.org").get("/status/200").text(); console.log(text); // -> { "code": 200, "description": "OK" } ``` -------------------------------- ### Manual JSON request setup with fetch Source: https://github.com/elbywan/wretch/blob/master/README.md Shows the manual setup required for sending JSON data with Fetch, including setting headers, method, and body. ```javascript fetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ "hello": "world" }) }).then(response => {/* … */}) // Omitting the data retrieval and error management parts… ``` -------------------------------- ### Installation via npm Source: https://github.com/elbywan/wretch/blob/master/README.md Command to install Wretch using npm. ```sh npm i wretch # or yarn/pnpm add wretch ``` -------------------------------- ### Install Wretch Source: https://github.com/elbywan/wretch/blob/master/docs/index.html Install Wretch using various package managers or CDN. ```bash npm i wretch ``` ```bash yarn add wretch ``` ```bash pnpm add wretch ``` ```bash bun add wretch ``` ```html ``` -------------------------------- ### get example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Basic example of performing a GET request. ```typescript wretch("...").get(); ``` -------------------------------- ### Install dependencies Source: https://github.com/elbywan/wretch/blob/master/CONTRIBUTING.md Command to install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Upload progress monitoring with progress addon Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V2_V3.md v3 adds upload progress monitoring support through the Progress addon. This example demonstrates its usage. ```javascript import wretch from "wretch" import ProgressAddon from "wretch/addons/progress" import FormDataAddon from "wretch/addons/formData" await wretch("https://httpbingo.org/post") .addon([ProgressAddon(), FormDataAddon]) .formData({ file }) .onUpload((loaded, total) => { console.log(`Upload: ${(loaded / total * 100).toFixed(0)}%`) }) .post() .json() ``` -------------------------------- ### ProgressAddon Usage Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/addons_progress.ProgressAddon.html Example demonstrating how to use the ProgressAddon to track download progress. ```typescript import ProgressAddon from "wretch/addons/progress" wretch("some_url") .addon(ProgressAddon()) .onDownload((loaded, total) => console.log(`Download: ${(loaded / total * 100).toFixed(0)}%`)) .get() .res() ``` -------------------------------- ### Config Directive Example Source: https://github.com/elbywan/wretch/blob/master/test/snippets/examples/README.md An example of a config directive to modify the execution context. ```typescript { type: 'config', name: 'withTimeout', handler: (snippet, directive, context) => { return { timeout: parseInt(directive.args[0]) } } } ``` -------------------------------- ### Benchmark Plugin Example Source: https://github.com/elbywan/wretch/blob/master/test/snippets/README.md Example of creating and configuring a benchmark plugin for Wretch. ```typescript import { createBenchmarkPlugin } from './snippets/examples/benchmark-plugin.js' const benchmark = createBenchmarkPlugin({ threshold: 100, // Warn if > 100ms printPerTest: false, // Print per-test results printSummary: true // Print summary report }) const runner = new SnippetRunner({ plugins: [benchmark] }) ``` -------------------------------- ### onUpload Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/addons_progress.ProgressAddon.html Example of how to use the onUpload method to track upload progress. ```typescript import ProgressAddon from "wretch/addons/progress" wretch("https://example.com/upload") // Note: HTTPS required for Chrome .addon(ProgressAddon()) .onUpload((loaded, total) => console.log(`Upload: ${(loaded / total * 100).toFixed(0)}%`)) .post(formData) .res() ``` -------------------------------- ### Complete request/response chain example Source: https://github.com/elbywan/wretch/blob/master/README.md Complete request/response chain example ```javascript await wretch("https://api.example.com") // Base URL .headers({ "X-Api-Key": "secret" }) // Helper method .query({ limit: 10 }) // Helper method .json({ name: "Alice", role: "admin" }) // Body type .post("/users") // HTTP method (starts request) .badRequest(err => console.log("Invalid")) // Catcher .unauthorized(err => console.log("No auth")) // Catcher .json(user => console.log(user)) // Response type ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/elbywan/wretch/blob/master/test/snippets/README.md Example of a Wretch snippet testing system configuration using JSON. ```json { "files": ["README.md", "docs/**/*.md"], "languages": ["typescript", "javascript"], "includeUndirected": false, "timeout": 5000, "showSuccess": true, "showSkipped": false, "verbose": false, "plugins": ["./my-plugin.js"], "globals": { "API_URL": "https://api.example.com" } } ``` -------------------------------- ### Replay Function Renamed - Before (v1) Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V1_V2.md Example of using the .replay() function in v1. ```javascript wretch("...").replay() ``` -------------------------------- ### Minimal Plugin Example Source: https://github.com/elbywan/wretch/blob/master/test/snippets/examples/README.md A basic example of a plugin object implementing the `Plugin` interface, including optional directives and lifecycle hooks. ```typescript import type { Plugin } from '../plugin.js' export const myPlugin: Plugin = { name: 'my-plugin', version: '1.0.0', description: 'Does something useful', // Optional: Register custom directives directives: [ { type: 'control', name: 'myDirective', description: 'My custom directive', handler: (snippet, directive) => { // Return null to continue, or { skip: true, reason: '...' } to skip return null } } ], // Optional: Lifecycle hooks hooks: { onInit: async () => { console.log('Plugin initialized') }, onBeforeRun: async (snippet, context) => { // Modify context or return undefined to continue return undefined }, onAfterRun: async (snippet, result) => { // Modify result or return undefined to keep original return undefined }, onTestComplete: async (testResult) => { // Modify test result or return undefined return undefined }, onComplete: async (results) => { console.log(`Completed ${results.length} tests`) }, onError: async (error, snippet) => { console.error('Error:', error.message) } }, // Optional: Plugin lifecycle onLoad: async () => { console.log('Plugin loaded') }, onUnload: async () => { console.log('Plugin unloaded') } } ``` -------------------------------- ### JavaScript Configuration Example Source: https://github.com/elbywan/wretch/blob/master/test/snippets/README.md Example of a Wretch snippet testing system configuration using JavaScript. ```javascript // snippet-test.config.js export default { files: ["README.md", "docs/**/*.md"], languages: ["typescript", "javascript"], timeout: 5000, // Load plugins plugins: ["./my-plugin.js"], // Custom module resolver moduleResolver: async (specifier) => { if (specifier === 'my-lib') { return await import('./lib/index.js') } }, // Global variables available in snippets globals: { API_URL: process.env.API_URL || "https://api.example.com" } } ``` -------------------------------- ### Usage Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/addons_progress.ProgressResolver.html Example of how to use the progress addon to track download progress. ```typescript import ProgressAddon from "wretch/addons/progress" wretch("some_url") .addon(ProgressAddon()) .get() .progress((loaded, total) => console.log(`${(loaded / total * 100).toFixed(0)}%`)) ``` -------------------------------- ### Logging Plugin Example Source: https://github.com/elbywan/wretch/blob/master/test/snippets/README.md Example of creating and configuring a logging plugin for Wretch. ```typescript import { createLoggingPlugin } from './snippets/examples/logging-plugin.js' const logger = createLoggingPlugin({ logStart: true, // Log when tests start logComplete: true, // Log when tests complete logErrors: true, // Log errors mode: 'console' // 'console' or 'collect' }) const runner = new SnippetRunner({ plugins: [logger] }) ``` -------------------------------- ### Bun Usage Source: https://github.com/elbywan/wretch/blob/master/README.md Basic Bun usage example ```bash bun add wretch ``` -------------------------------- ### Context Middleware Example Source: https://github.com/elbywan/wretch/blob/master/README.md Context middleware for data exposure. ```javascript const contextMiddleware = (next) => (url, opts) => { if (opts.context) { // Mutate "context" opts.context.property = "anything"; } return next(url, opts); }; // Provide the reference to a "context" object const context = {}; const res = await wretch("https://httpbingo.org/get") // Pass "context" by reference as an option .options({ context }) .middlewares([contextMiddleware]) .get() .res(); console.log(context.property); // prints "anything" ``` -------------------------------- ### HTTP Methods Extra Argument - Before (v1) Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V1_V2.md Example of passing fetch options as an argument to HTTP methods in v1. ```javascript wretch("...").get({ my: "option" }) ``` -------------------------------- ### Control Directive Example Source: https://github.com/elbywan/wretch/blob/master/test/snippets/examples/README.md An example of a control directive that can skip test flow. ```typescript { type: 'control', name: 'myControl', handler: (snippet, directive) => { if (shouldSkip(snippet)) { return { skip: true, reason: 'Not ready' } } return null } } ``` -------------------------------- ### Assertion Directive Example Source: https://github.com/elbywan/wretch/blob/master/test/snippets/examples/README.md An example of an assertion directive to validate execution results. ```typescript { type: 'assertion', name: 'expectCustom', handler: (executionResult, directive) => { const passed = validate(executionResult.returnValue) return { passed, message: passed ? undefined : 'Validation failed', actual: executionResult.returnValue, expected: directive.args[0] } } } ``` -------------------------------- ### Accept Header Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of setting the Accept header using the accept helper. ```javascript wretch("...").accept("application/json"); ``` -------------------------------- ### POST Request Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of performing a POST request with Wretch. ```javascript wretch("...").json({...}).post() ``` -------------------------------- ### OPTIONS Request Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of performing an OPTIONS request using Wretch. ```javascript wretch("...").opts(); ``` -------------------------------- ### fetch example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of using fetch to replay requests, including re-authentication on 401 errors. ```typescript const reAuthOn401 = wretch().catcher(401, async (error, request) => { // Renew credentials const token = await wretch("/renewtoken").get().text(); storeToken(token); // Replay the original request with new credentials return request.auth(token).fetch().unauthorized((err) => { throw err; }).json();});reAuthOn401.get("/resource").json() // <- Will only be called for the original promise.then(callback); // <- Will be called for the original OR the replayed promise result ``` -------------------------------- ### Auth method example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Shortcut to set the "Authorization" header. ```javascript wretch("...").auth("Basic d3JldGNoOnJvY2tz"); ``` -------------------------------- ### Registering Addons Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Examples of how to register single or multiple addons. ```typescript import FormDataAddon from "wretch/addons/formData" import QueryStringAddon from "wretch/addons/queryString" // Add a single addon const w = wretch().addon(FormDataAddon) // Or add multiple addons at once const w2 = wretch().addon([FormDataAddon, QueryStringAddon]) // Additional features are now available w.formData({ hello: "world" }).query({ check: true }) ``` -------------------------------- ### Controller Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/addons_abort.AbortResolver.html Example demonstrating how to get the AbortController from the chain and use it later. ```typescript const [c, w] = wretch("url") .addon(AbortAddon()) .get() .controller() // Resume with the chain w.onAbort(_ => console.log("ouch")).json() // Later on… c.abort() ``` -------------------------------- ### Setting Fetch Options Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of setting fetch options using the `options` method. ```javascript wretch("...").options({ credentials: "same-origin" }); ``` -------------------------------- ### Replay Function Renamed - After (v2) Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V1_V2.md Example of using the renamed .fetch() function in v2. ```javascript wretch("...").fetch() ``` -------------------------------- ### Replace/Mixin Arguments - Before (v1) Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V1_V2.md Example of using inconsistent 'mixin' or 'replace' arguments in v1. ```javascript // false: do not merge the value wretch.options({ credentials: "same-origin" }, false) ``` -------------------------------- ### Benchmark Plugin Usage Source: https://github.com/elbywan/wretch/blob/master/test/snippets/examples/README.md Shows how to use the default benchmark plugin and how to create a customized instance with specific options like threshold, printPerTest, printSummary, and a custom formatter. ```typescript import { benchmarkPlugin, createBenchmarkPlugin } from './snippets/examples/benchmark-plugin.js' import { SnippetRunner } from './snippets/index.js' // Use the default instance const runner = new SnippetRunner({ plugins: [benchmarkPlugin] }) // Or create a customized instance const customBenchmark = createBenchmarkPlugin({ threshold: 50, // Warn if execution takes > 50ms printPerTest: true, // Print timing for each test printSummary: true, // Print summary at end formatter: (result) => `${result.file} took ${result.duration}ms` }) const runner2 = new SnippetRunner({ plugins: [customBenchmark] }) ``` -------------------------------- ### Replace/Mixin Arguments - After (v2) Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V1_V2.md Example of consistently using 'replace = false' arguments in v2, often with per-instance configuration. ```javascript // Use per-instance configuration instead of global const api = wretch("https://api.example.com", { credentials: "same-origin" }) ``` -------------------------------- ### Logging Plugin Usage Source: https://github.com/elbywan/wretch/blob/master/test/snippets/examples/README.md Demonstrates how to use the default logging plugin instance and how to create a customized instance with specific options. ```typescript import { loggingPlugin, createLoggingPlugin } from './snippets/examples/logging-plugin.js' import { SnippetRunner } from './snippets/index.js' // Use the default instance const runner = new SnippetRunner({ plugins: [loggingPlugin] }) // Or create a customized instance const customLogger = createLoggingPlugin({ logStart: true, logComplete: true, logErrors: true, mode: 'console' }) const runner2 = new SnippetRunner({ plugins: [customLogger] }) ``` -------------------------------- ### HTTP Methods Extra Argument - After (v2) Source: https://github.com/elbywan/wretch/blob/master/MIGRATION_V1_V2.md Example of the extra argument now appending a URL segment in v2, with options set via .options(). ```javascript wretch("https://base.com").get("/resource/1") // To set options, use .options() before calling the HTTP method wretch("...") .options({ my: "option" }) .get() ``` -------------------------------- ### Helper Methods Example Source: https://github.com/elbywan/wretch/blob/master/README.md Chaining helper methods to configure a request. ```javascript let api = wretch("http://domain.com/") api = api .url("/posts/1") .headers({ "Cache-Control": "no-cache" }) .content("text/html") ``` -------------------------------- ### Transform Directive Example Source: https://github.com/elbywan/wretch/blob/master/test/snippets/examples/README.md An example of a transform directive to modify code before execution. ```typescript { type: 'transform', name: 'wrapInTry', handler: (snippet, directive) => { return { code: `try {\n${snippet.code}\n} catch (e) { console.error(e) }`, modified: true } } } ``` -------------------------------- ### HTTP Methods with URL and Body Arguments Source: https://github.com/elbywan/wretch/blob/master/README.md Demonstrates HTTP method shortcuts with optional url and body arguments, and their equivalent longer forms. ```javascript const api = wretch("http://jsonplaceholder.typicode.com") // These shorthands: api.get("/posts"); api.post({ json: "body" }, "/posts"); // Are equivalent to: api.url("/posts").get(); api.json({ json: "body" }).url("/posts").post(); ``` -------------------------------- ### Importing the Abort addon Source: https://github.com/elbywan/wretch/blob/master/README.md Importing the Abort addon ```javascript import AbortAddon from "wretch/addons/abort" ``` -------------------------------- ### Using multiple middlewares with wretch Source: https://github.com/elbywan/wretch/blob/master/README.md Demonstrates how to use multiple middlewares with wretch. ```javascript import wretch from "wretch" import { retry, dedupe } from "wretch/middlewares" const w = wretch().middlewares([retry(), dedupe()]) ``` -------------------------------- ### SetTimeout Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/addons_abort.AbortResolver.html Example showing how to set a timeout for a request. ```typescript // 1 second timeout wretch("...").addon(AbortAddon()).get().setTimeout(1000).json(_ => // will not be called if the request timeouts) // With custom controller wretch("...").addon(AbortAddon()).get().setTimeout(1000, { controller }).json() ``` -------------------------------- ### Import and use queryStringAddon Source: https://github.com/elbywan/wretch/blob/master/docs/api/variables/addons.queryStringAddon.html Demonstrates how to import and use the queryStringAddon with wretch. ```javascript import QueryAddon from "wretch/addons/queryString" wretch().addon(QueryAddon) ``` -------------------------------- ### catcherFallback Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of using catcherFallback to handle uncaught errors. ```javascript wretch(url) .catcher(404, err => redirect("/routes/notfound", err.message)) .catcher(500, err => flashMessage("internal.server.error")) // this fallback will trigger for any error except the ones caught above (404 and 505) .catcherFallback(err => { log("Uncaught error:", err) throw err }) ``` -------------------------------- ### PUT Request Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of performing a PUT request with Wretch. ```javascript wretch("...").json({...}).put() ``` -------------------------------- ### Download Progress Tracking Source: https://github.com/elbywan/wretch/blob/master/README.md Adds the ability to monitor progress when downloading. ```javascript import ProgressAddon from "wretch/addons/progress" await wretch("https://httpbingo.org/bytes/5000") .addon(ProgressAddon()) .get() // Called with the number of bytes loaded and the total number of bytes to load .progress((loaded, total) => { console.log(`Download: ${(loaded / total * 100).toFixed(0)}%`) }) .blob() ``` -------------------------------- ### File Upload with Progress Source: https://github.com/elbywan/wretch/blob/master/README.md File upload with progress tracking using addons ```javascript // 📤 File Upload with Progress import ProgressAddon from "wretch/addons/progress" import FormDataAddon from "wretch/addons/formData" await wretch("https://httpbingo.org/post") .addon([FormDataAddon, ProgressAddon()]) .formData({ file: file }) .post() .progress((loaded, total) => console.log(`${(loaded/total*100).toFixed()}%`)) .json() ``` -------------------------------- ### Lint, Build and Test Source: https://github.com/elbywan/wretch/blob/master/CONTRIBUTING.md Commands for running linting, building, and testing the project. ```bash npm start ``` ```bash npm run test:browser # same as the ci npm run test:browser:watch # in watch mode ``` -------------------------------- ### Skip Function Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/types/middlewares_retry.RetryOptions.html Example of a skip function that prevents retrying non-GET requests. ```typescript (url, options) => ( options.method !== "GET") ``` -------------------------------- ### Factory method usage example Source: https://github.com/elbywan/wretch/blob/master/README.md Illustrates different ways to use factory methods like .json() to set the response body type. It shows usage without a callback, with await, and with a callback that returns a value. ```javascript const ENDPOINT = "https://jsonplaceholder.typicode.com/posts/1" // Without a callback wretch(ENDPOINT) .get() .json() .then(json => { /* the json argument is the parsed json of the response body */ }) // Without a callback using await const json = await wretch(ENDPOINT).get().json() // With a callback the value returned is passed to the Promise wretch(ENDPOINT).get().json(json => "Hello world!").then(console.log) // => Hello world! ``` -------------------------------- ### content Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of using the content method to set the Content-Type header. ```javascript wretch("...").content("application/json"); ``` -------------------------------- ### Custom Fetch Implementation Source: https://github.com/elbywan/wretch/blob/master/README.md Custom fetch implementation with logging and timing ```javascript import wretch from "wretch" // Per-instance custom fetch const api = wretch("https://jsonplaceholder.typicode.com") .fetchPolyfill((url, opts) => { console.log('Fetching:', url) console.time(url) return fetch(url, opts).finally(() => { console.timeEnd(url) }) }) await api.get("/posts").json() ``` -------------------------------- ### Instantiating wretch with base URL and options Source: https://github.com/elbywan/wretch/blob/master/README.md Instantiating wretch with base URL and options ```typescript import wretch from "wretch" const api = wretch("http://domain.com/", { cache: "default" }) ``` -------------------------------- ### Using Plugins Source: https://github.com/elbywan/wretch/blob/master/test/snippets/README.md Demonstrates how to initialize a SnippetRunner with multiple plugins and run snippets. ```typescript import { SnippetRunner } from './snippets/index.js' import { benchmarkPlugin, loggingPlugin } from './snippets/examples/index.js' const runner = new SnippetRunner({ plugins: [benchmarkPlugin, loggingPlugin] }) // Initialize plugins await runner.initialize() // Run tests with plugins active const results = await runner.runSnippets(snippets) // Cleanup plugins await runner.cleanup() ``` -------------------------------- ### HEAD Request Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of performing a HEAD request using Wretch. ```javascript wretch("...").head(); ``` -------------------------------- ### Body Types Example Source: https://github.com/elbywan/wretch/blob/master/README.md Specifying a body type for uploading data. ```javascript let api = wretch("http://domain.com/") api = api.body("
") api ``` -------------------------------- ### Using abortAddon with AbortController and signal Source: https://github.com/elbywan/wretch/blob/master/docs/api/variables/addons.abortAddon.html Example demonstrating how to use abortAddon with a native AbortController and the signal method. ```javascript const controller = new AbortController(); wretch("...") .addon(AbortAddon()) .signal(controller) .get() .onAbort((_) => console.log("Aborted !")) .text((_) => console.log("should never be called")); controller.abort(); ``` -------------------------------- ### Reusable wretch instances with base configuration Source: https://github.com/elbywan/wretch/blob/master/README.md Illustrates creating reusable Wretch instances with base URLs, authentication, and custom error handling. ```javascript const token = "MY_SECRET_TOKEN" // Cross origin authenticated requests on an external API const externalApi = wretch("https://jsonplaceholder.typicode.com") // Base url // Authorization header .auth(`Bearer ${token}`) // Cors fetch options .options({ credentials: "include", mode: "cors" }) // Handle 403 errors .resolve((w) => w.forbidden(error => { /* Handle all 403 errors */ })); // Fetch a resource const resource = await externalApi // Add a custom header for this request .headers({ "If-Unmodified-Since": "Wed, 21 Oct 2015 07:28:00 GMT" }) .get("/posts/1") .json(() => {/* do something with the resource */}); // Post a resource externalApi .url("/posts") .post({ "Shiny new": "resource object" }) .json(() => {/* do something with the created resource */}); ``` -------------------------------- ### PATCH Request Example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Example of performing a PATCH request with a JSON body using Wretch. ```javascript wretch("...").json({...}).patch() ``` -------------------------------- ### Adding multiple addons to wretch instance Source: https://github.com/elbywan/wretch/blob/master/README.md Adding multiple addons to wretch instance ```javascript import FormDataAddon from "wretch/addons/formData" import QueryStringAddon from "wretch/addons/queryString" // Add both addons const w = wretch().addon([FormDataAddon, QueryStringAddon]) // Additional features are now available w.formData({ hello: "world" }).query({ check: true }) ``` -------------------------------- ### UMD import via script tag Source: https://github.com/elbywan/wretch/blob/master/README.md Example of including Wretch in an HTML file using a UMD bundle via a script tag. ```html ``` -------------------------------- ### Query string construction from objects and strings Source: https://github.com/elbywan/wretch/blob/master/README.md Query string construction from objects and strings ```javascript import QueryStringAddon from "wretch/addons/queryString" let w = wretch("http://example.com").addon(QueryStringAddon); // url is http://example.com w = w.query({ a: 1, b: 2 }); // url is now http://example.com?a=1&b=2 w = w.query({ c: 3, d: [4, 5] }); // url is now http://example.com?a=1&b=2c=3&d=4&d=5 w = w.query("five&six&seven=eight"); // url is now http://example.com?a=1&b=2c=3&d=4&d=5&five&six&seven=eight w = w.query({ reset: true }, { replace: true }); // url is now http://example.com?reset=true ``` -------------------------------- ### GET /{url} Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Performs an HTTP GET request. Can be called without parameters to fetch the current URL or with a URL parameter to fetch a specific resource. ```APIDOC ## GET /{url} ### Description Performs a [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request. ### Method GET ### Endpoint /{url} ### Parameters #### Path Parameters - **this** (Self & Wretch) - Required - The Wretch instance #### Query Parameters - **url** (string) - Optional - URL to append to the request #### Request Body No request body parameters ### Request Example ```javascript wretch("...").get(); ``` ### Response #### Success Response (200) - **responseChain** (Chain & WretchResponseChain | Resolver) - The response chain or resolver based on type constraints #### Response Example Returns a promise chain for handling the GET response ``` -------------------------------- ### Modern import via script tag Source: https://github.com/elbywan/wretch/blob/master/README.md Example of importing Wretch using modern ES Module syntax in an HTML file. ```html ``` -------------------------------- ### Loading Configuration Source: https://github.com/elbywan/wretch/blob/master/test/snippets/README.md Demonstrates how to load Wretch configuration files automatically or from a specific path, and use them with SnippetRunner. ```typescript import { loadConfig, SnippetRunner } from './snippets/index.js' // Automatically discover and load config from current directory const config = await loadConfig() // Or load from specific path const config = await loadConfig('/path/to/config.json') // Use config with runner const runner = new SnippetRunner(config) ``` -------------------------------- ### Request replay with credential renewal Source: https://github.com/elbywan/wretch/blob/master/README.md An example demonstrating how to replay a request, specifically in a scenario where credentials need to be renewed after an unauthorized (401) error. ```javascript await wretch("https://httpbingo.org/basic-auth/user/pass") .addon(BasicAuthAddon) .basicAuth("user", "wrongpass") .get() .unauthorized(async (error, req) => { // Renew credentials const password = await wretch("https://httpbingo.org/base64/decode/cGFzcw==").get().text(); // Replay the original request with new credentials return req .basicAuth("user", password) .fetch() .unauthorized((err) => { throw err }) .json(); }) .json() // The promise chain is preserved as expected // ".then" will be performed on the result of the original request // or the replayed one (if a 401 error was thrown) .then(() => { /* … */ }); ``` -------------------------------- ### Perform GET request with Wretch Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.Wretch.html Issues an HTTP GET request via Wretch’s fluent API. Accepts an optional URL and returns a resolver for further processing of the response. Ideal for retrieving data from a server. ```javascript wretch("...").get(); ``` -------------------------------- ### blob example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.WretchResponseChain.html Reads the payload and deserializes it as a Blob. ```typescript wretch("...").get().blob(blob => …) ``` -------------------------------- ### Using abortAddon with onAbort and controller Source: https://github.com/elbywan/wretch/blob/master/docs/api/variables/addons.abortAddon.html Example demonstrating how to use abortAddon to abort requests with an explicit controller and the onAbort callback. ```javascript import AbortAddon from "wretch/addons/abort" const [c, w] = wretch("...") .addon(AbortAddon()) .get() .onAbort((_) => console.log("Aborted !")) .controller(); w.text((_) => console.log("should never be called")); c.abort(); ``` -------------------------------- ### formData example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.WretchResponseChain.html Reads the payload and deserializes it as a FormData object. ```typescript wretch("...").get().formData(formData => …) ``` -------------------------------- ### arrayBuffer example Source: https://github.com/elbywan/wretch/blob/master/docs/api/interfaces/index.WretchResponseChain.html Reads the payload and deserializes it as an ArrayBuffer object. ```typescript wretch("...").get().arrayBuffer(arrayBuffer => …) ``` -------------------------------- ### Benchmark Plugin Directive Usage Source: https://github.com/elbywan/wretch/blob/master/test/snippets/examples/README.md Illustrates how to use the `snippet:benchmark` directive within markdown to measure the execution time of a specific snippet. ```markdown ````markdown ```typescript function expensiveOperation() { // This snippet's execution time will be measured return 42; } ``` ```` ``` -------------------------------- ### Multi-line descriptions Source: https://github.com/elbywan/wretch/blob/master/test/snippets/README.md Example of using multi-line descriptions for snippets. ```markdown ```js // code here ``` ``` -------------------------------- ### Theme Initialization Source: https://github.com/elbywan/wretch/blob/master/docs/api/modules/index.html This script initializes the theme based on local storage or OS preference and controls the initial display of the body. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Skip a snippet entirely Source: https://github.com/elbywan/wretch/blob/master/test/snippets/README.md Example of skipping a snippet with a reason. ```markdown ```js wretch("http://localhost:3000").get() ``` ``` -------------------------------- ### Header case sensitivity example Source: https://github.com/elbywan/wretch/blob/master/README.md Demonstrates how the Headers class in the Fetch API is case-insensitive, appending values to the same key regardless of case. ```javascript const headers = new Headers(); headers.append("Accept", "application/json"); headers.append("accept", "application/json"); headers.forEach((value, key) => console.log(key, value)); // prints: accept application/json, application/json ```