Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

openapi-fetch

Package Overview
Dependencies
Maintainers
1
Versions
69
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

openapi-fetch - npm Package Compare versions

Comparing version 0.13.0 to 0.13.1

6

CHANGELOG.md
# openapi-fetch
## 0.13.1
### Patch Changes
- [#1974](https://github.com/openapi-ts/openapi-typescript/pull/1974) [`35c576c`](https://github.com/openapi-ts/openapi-typescript/commit/35c576c8b2852f66e641014d13ffcfdeb21e98a1) Thanks [@luchsamapparat](https://github.com/luchsamapparat)! - add onError handler to middleware
## 0.13.0

@@ -4,0 +10,0 @@

12

dist/index.d.ts

@@ -9,4 +9,4 @@ import type {

PathsWithMethod,
RequiredKeysOf,
ResponseObjectMap,
RequiredKeysOf,
SuccessResponse,

@@ -156,2 +156,5 @@ } from "openapi-typescript-helpers";

) => void | Response | undefined | Promise<Response | undefined | void>;
type MiddlewareOnError = (
options: MiddlewareCallbackParams & { error: unknown },
) => void | Response | Error | Promise<void | Response | Error>;

@@ -162,2 +165,3 @@ export type Middleware =

onResponse?: MiddlewareOnResponse;
onError?: MiddlewareOnError;
}

@@ -167,2 +171,8 @@ | {

onResponse: MiddlewareOnResponse;
onError?: MiddlewareOnError;
}
| {
onRequest?: MiddlewareOnRequest;
onResponse?: MiddlewareOnResponse;
onError: MiddlewareOnError;
};

@@ -169,0 +179,0 @@

@@ -127,4 +127,46 @@ // settings & const

// fetch!
let response = await fetch(request);
let response;
try {
response = await fetch(request);
} catch (error) {
let errorAfterMiddleware = error;
// middleware (error)
// execute in reverse-array order (first priority gets last transform)
if (middlewares.length) {
for (let i = middlewares.length - 1; i >= 0; i--) {
const m = middlewares[i];
if (m && typeof m === "object" && typeof m.onError === "function") {
const result = await m.onError({
request,
error: errorAfterMiddleware,
schemaPath,
params,
options,
id,
});
if (result) {
// if error is handled by returning a response, skip remaining middleware
if (result instanceof Response) {
errorAfterMiddleware = undefined;
response = result;
break;
}
if (result instanceof Error) {
errorAfterMiddleware = result;
continue;
}
throw new Error("onError: must return new Response() or instance of Error");
}
}
}
}
// rethrow error if not handled by middleware
if (errorAfterMiddleware) {
throw errorAfterMiddleware;
}
}
// middleware (response)

@@ -217,4 +259,4 @@ // execute in reverse-array order (first priority gets last transform)

}
if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m)) {
throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");
if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) {
throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
}

@@ -221,0 +263,0 @@ middlewares.push(m);

@@ -9,4 +9,4 @@ import type {

PathsWithMethod,
RequiredKeysOf,
ResponseObjectMap,
RequiredKeysOf,
SuccessResponse,

@@ -156,2 +156,5 @@ } from "openapi-typescript-helpers";

) => void | Response | undefined | Promise<Response | undefined | void>;
type MiddlewareOnError = (
options: MiddlewareCallbackParams & { error: unknown },
) => void | Response | Error | Promise<void | Response | Error>;

@@ -162,2 +165,3 @@ export type Middleware =

onResponse?: MiddlewareOnResponse;
onError?: MiddlewareOnError;
}

@@ -167,2 +171,8 @@ | {

onResponse: MiddlewareOnResponse;
onError?: MiddlewareOnError;
}
| {
onRequest?: MiddlewareOnRequest;
onResponse?: MiddlewareOnResponse;
onError: MiddlewareOnError;
};

@@ -169,0 +179,0 @@

2

dist/index.min.js

@@ -1,1 +0,1 @@

var v=/\{[^{}]+\}/g;function W(){return Math.random().toString(36).slice(2,11)}function H(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:o,headers:l,...c}={...n};e=D(e);let d=[];async function h(a,s){let{baseUrl:m,fetch:C=i,Request:_=t,headers:N,params:b={},parseAs:T="json",querySerializer:R,bodySerializer:q=o??M,body:U,...j}=s||{};m&&(e=D(m));let x=typeof r=="function"?r:P(r);R&&(x=typeof R=="function"?R:P({...typeof r=="object"?r:{},...R}));let E=U===void 0?void 0:q(U),k=E===void 0||E instanceof FormData?{}:{"Content-Type":"application/json"},B={redirect:"follow",...c,...j,body:E,headers:J(k,l,N,b.header)},g,A,p=new t(Q(a,{baseUrl:e,params:b,querySerializer:x}),B);for(let f in j)f in p||(p[f]=j[f]);if(d.length){g=W(),A=Object.freeze({baseUrl:e,fetch:C,parseAs:T,querySerializer:x,bodySerializer:q});for(let f of d)if(f&&typeof f=="object"&&typeof f.onRequest=="function"){let y=await f.onRequest({request:p,schemaPath:a,params:b,options:A,id:g});if(y){if(!(y instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");p=y}}}let u=await C(p);if(d.length)for(let f=d.length-1;f>=0;f--){let y=d[f];if(y&&typeof y=="object"&&typeof y.onResponse=="function"){let $=await y.onResponse({request:p,response:u,schemaPath:a,params:b,options:A,id:g});if($){if(!($ instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");u=$}}}if(u.status===204||u.headers.get("Content-Length")==="0")return u.ok?{data:void 0,response:u}:{error:void 0,response:u};if(u.ok)return T==="stream"?{data:u.body,response:u}:{data:await u[T](),response:u};let S=await u.text();try{S=JSON.parse(S)}catch{}return{error:S,response:u}}return{GET(a,s){return h(a,{...s,method:"GET"})},PUT(a,s){return h(a,{...s,method:"PUT"})},POST(a,s){return h(a,{...s,method:"POST"})},DELETE(a,s){return h(a,{...s,method:"DELETE"})},OPTIONS(a,s){return h(a,{...s,method:"OPTIONS"})},HEAD(a,s){return h(a,{...s,method:"HEAD"})},PATCH(a,s){return h(a,{...s,method:"PATCH"})},TRACE(a,s){return h(a,{...s,method:"TRACE"})},use(...a){for(let s of a)if(s){if(typeof s!="object"||!("onRequest"in s||"onResponse"in s))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");d.push(s)}},eject(...a){for(let s of a){let m=d.indexOf(s);m!==-1&&d.splice(m,1)}}}}var O=class{constructor(e,t){this.client=e,this.url=t}GET(e){return this.client.GET(this.url,e)}PUT(e){return this.client.PUT(this.url,e)}POST(e){return this.client.POST(this.url,e)}DELETE(e){return this.client.DELETE(this.url,e)}OPTIONS(e){return this.client.OPTIONS(this.url,e)}HEAD(e){return this.client.HEAD(this.url,e)}PATCH(e){return this.client.PATCH(this.url,e)}TRACE(e){return this.client.TRACE(this.url,e)}},z=class{constructor(){this.client=null}get(e,t){let i=new O(e,t);return this.client[t]=i,i}};function F(n){let e=new z,t=new Proxy(n,e);function i(){}i.prototype=t;let r=new i;return e.client=r,r}function K(n){return F(H(n))}function w(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${t?.allowReserved===!0?e:encodeURIComponent(e)}`}function I(n,e,t){if(!e||typeof e!="object")return"";let i=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(let c in e)i.push(c,t.allowReserved===!0?e[c]:encodeURIComponent(e[c]));let l=i.join(",");switch(t.style){case"form":return`${n}=${l}`;case"label":return`.${l}`;case"matrix":return`;${n}=${l}`;default:return l}}for(let l in e){let c=t.style==="deepObject"?`${n}[${l}]`:l;i.push(w(c,e[l],t))}let o=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${o}`:o}function L(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){let o={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",l=(t.allowReserved===!0?e:e.map(c=>encodeURIComponent(c))).join(o);switch(t.style){case"simple":return l;case"label":return`.${l}`;case"matrix":return`;${n}=${l}`;default:return`${n}=${l}`}}let i={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(let o of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?o:encodeURIComponent(o)):r.push(w(n,o,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function P(n){return function(t){let i=[];if(t&&typeof t=="object")for(let r in t){let o=t[r];if(o!=null){if(Array.isArray(o)){if(o.length===0)continue;i.push(L(r,o,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof o=="object"){i.push(I(r,o,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}i.push(w(r,o,n))}}return i.join("&")}}function G(n,e){let t=n;for(let i of n.match(v)??[]){let r=i.substring(1,i.length-1),o=!1,l="simple";if(r.endsWith("*")&&(o=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(l="label",r=r.substring(1)):r.startsWith(";")&&(l="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;let c=e[r];if(Array.isArray(c)){t=t.replace(i,L(r,c,{style:l,explode:o}));continue}if(typeof c=="object"){t=t.replace(i,I(r,c,{style:l,explode:o}));continue}if(l==="matrix"){t=t.replace(i,`;${w(r,c)}`);continue}t=t.replace(i,l==="label"?`.${encodeURIComponent(c)}`:encodeURIComponent(c))}return t}function M(n){return n instanceof FormData?n:JSON.stringify(n)}function Q(n,e){let t=`${e.baseUrl}${n}`;e.params?.path&&(t=G(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function J(...n){let e=new Headers;for(let t of n){if(!t||typeof t!="object")continue;let i=t instanceof Headers?t.entries():Object.entries(t);for(let[r,o]of i)if(o===null)e.delete(r);else if(Array.isArray(o))for(let l of o)e.append(r,l);else o!==void 0&&e.set(r,o)}return e}function D(n){return n.endsWith("/")?n.substring(0,n.length-1):n}export{Q as createFinalURL,K as createPathBasedClient,P as createQuerySerializer,H as default,M as defaultBodySerializer,G as defaultPathSerializer,J as mergeHeaders,W as randomID,D as removeTrailingSlash,L as serializeArrayParam,I as serializeObjectParam,w as serializePrimitiveParam,F as wrapAsPathBasedClient};
var F=/\{[^{}]+\}/g;function G(){return Math.random().toString(36).slice(2,11)}function L(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:o,headers:l,...a}={...n};e=I(e);let h=[];async function p(c,s){let{baseUrl:b,fetch:U=i,Request:V=t,headers:B,params:w={},parseAs:A="json",querySerializer:E,bodySerializer:P=o??J,body:D,...S}=s||{};b&&(e=I(b));let $=typeof r=="function"?r:H(r);E&&($=typeof E=="function"?E:H({...typeof r=="object"?r:{},...E}));let O=D===void 0?void 0:P(D),v=O===void 0||O instanceof FormData?{}:{"Content-Type":"application/json"},W={redirect:"follow",...a,...S,body:O,headers:K(v,l,B,w.header)},T,j,y=new t(_(c,{baseUrl:e,params:w,querySerializer:$}),W);for(let u in S)u in y||(y[u]=S[u]);if(h.length){T=G(),j=Object.freeze({baseUrl:e,fetch:U,parseAs:A,querySerializer:$,bodySerializer:P});for(let u of h)if(u&&typeof u=="object"&&typeof u.onRequest=="function"){let d=await u.onRequest({request:y,schemaPath:c,params:w,options:j,id:T});if(d){if(!(d instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");y=d}}}let f;try{f=await U(y)}catch(u){let d=u;if(h.length)for(let m=h.length-1;m>=0;m--){let x=h[m];if(x&&typeof x=="object"&&typeof x.onError=="function"){let R=await x.onError({request:y,error:d,schemaPath:c,params:w,options:j,id:T});if(R){if(R instanceof Response){d=void 0,f=R;break}if(R instanceof Error){d=R;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(d)throw d}if(h.length)for(let u=h.length-1;u>=0;u--){let d=h[u];if(d&&typeof d=="object"&&typeof d.onResponse=="function"){let m=await d.onResponse({request:y,response:f,schemaPath:c,params:w,options:j,id:T});if(m){if(!(m instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");f=m}}}if(f.status===204||f.headers.get("Content-Length")==="0")return f.ok?{data:void 0,response:f}:{error:void 0,response:f};if(f.ok)return A==="stream"?{data:f.body,response:f}:{data:await f[A](),response:f};let z=await f.text();try{z=JSON.parse(z)}catch{}return{error:z,response:f}}return{GET(c,s){return p(c,{...s,method:"GET"})},PUT(c,s){return p(c,{...s,method:"PUT"})},POST(c,s){return p(c,{...s,method:"POST"})},DELETE(c,s){return p(c,{...s,method:"DELETE"})},OPTIONS(c,s){return p(c,{...s,method:"OPTIONS"})},HEAD(c,s){return p(c,{...s,method:"HEAD"})},PATCH(c,s){return p(c,{...s,method:"PATCH"})},TRACE(c,s){return p(c,{...s,method:"TRACE"})},use(...c){for(let s of c)if(s){if(typeof s!="object"||!("onRequest"in s||"onResponse"in s||"onError"in s))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");h.push(s)}},eject(...c){for(let s of c){let b=h.indexOf(s);b!==-1&&h.splice(b,1)}}}}var C=class{constructor(e,t){this.client=e,this.url=t}GET(e){return this.client.GET(this.url,e)}PUT(e){return this.client.PUT(this.url,e)}POST(e){return this.client.POST(this.url,e)}DELETE(e){return this.client.DELETE(this.url,e)}OPTIONS(e){return this.client.OPTIONS(this.url,e)}HEAD(e){return this.client.HEAD(this.url,e)}PATCH(e){return this.client.PATCH(this.url,e)}TRACE(e){return this.client.TRACE(this.url,e)}},q=class{constructor(){this.client=null}get(e,t){let i=new C(e,t);return this.client[t]=i,i}};function M(n){let e=new q,t=new Proxy(n,e);function i(){}i.prototype=t;let r=new i;return e.client=r,r}function X(n){return M(L(n))}function g(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${t?.allowReserved===!0?e:encodeURIComponent(e)}`}function k(n,e,t){if(!e||typeof e!="object")return"";let i=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(let a in e)i.push(a,t.allowReserved===!0?e[a]:encodeURIComponent(e[a]));let l=i.join(",");switch(t.style){case"form":return`${n}=${l}`;case"label":return`.${l}`;case"matrix":return`;${n}=${l}`;default:return l}}for(let l in e){let a=t.style==="deepObject"?`${n}[${l}]`:l;i.push(g(a,e[l],t))}let o=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${o}`:o}function N(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){let o={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",l=(t.allowReserved===!0?e:e.map(a=>encodeURIComponent(a))).join(o);switch(t.style){case"simple":return l;case"label":return`.${l}`;case"matrix":return`;${n}=${l}`;default:return`${n}=${l}`}}let i={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(let o of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?o:encodeURIComponent(o)):r.push(g(n,o,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function H(n){return function(t){let i=[];if(t&&typeof t=="object")for(let r in t){let o=t[r];if(o!=null){if(Array.isArray(o)){if(o.length===0)continue;i.push(N(r,o,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof o=="object"){i.push(k(r,o,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}i.push(g(r,o,n))}}return i.join("&")}}function Q(n,e){let t=n;for(let i of n.match(F)??[]){let r=i.substring(1,i.length-1),o=!1,l="simple";if(r.endsWith("*")&&(o=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(l="label",r=r.substring(1)):r.startsWith(";")&&(l="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;let a=e[r];if(Array.isArray(a)){t=t.replace(i,N(r,a,{style:l,explode:o}));continue}if(typeof a=="object"){t=t.replace(i,k(r,a,{style:l,explode:o}));continue}if(l==="matrix"){t=t.replace(i,`;${g(r,a)}`);continue}t=t.replace(i,l==="label"?`.${encodeURIComponent(a)}`:encodeURIComponent(a))}return t}function J(n){return n instanceof FormData?n:JSON.stringify(n)}function _(n,e){let t=`${e.baseUrl}${n}`;e.params?.path&&(t=Q(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function K(...n){let e=new Headers;for(let t of n){if(!t||typeof t!="object")continue;let i=t instanceof Headers?t.entries():Object.entries(t);for(let[r,o]of i)if(o===null)e.delete(r);else if(Array.isArray(o))for(let l of o)e.append(r,l);else o!==void 0&&e.set(r,o)}return e}function I(n){return n.endsWith("/")?n.substring(0,n.length-1):n}export{_ as createFinalURL,X as createPathBasedClient,H as createQuerySerializer,L as default,J as defaultBodySerializer,Q as defaultPathSerializer,K as mergeHeaders,G as randomID,I as removeTrailingSlash,N as serializeArrayParam,k as serializeObjectParam,g as serializePrimitiveParam,M as wrapAsPathBasedClient};
{
"name": "openapi-fetch",
"description": "Fast, type-safe fetch client for your OpenAPI schema. Only 6 kb (min). Works with React, Vue, Svelte, or vanilla JS.",
"version": "0.13.0",
"version": "0.13.1",
"author": {

@@ -63,3 +63,3 @@ "name": "Drew Powers",

"vite": "^5.4.10",
"openapi-typescript": "^7.4.2"
"openapi-typescript": "^7.4.4"
},

@@ -66,0 +66,0 @@ "scripts": {

@@ -9,4 +9,4 @@ import type {

PathsWithMethod,
RequiredKeysOf,
ResponseObjectMap,
RequiredKeysOf,
SuccessResponse,

@@ -156,2 +156,5 @@ } from "openapi-typescript-helpers";

) => void | Response | undefined | Promise<Response | undefined | void>;
type MiddlewareOnError = (
options: MiddlewareCallbackParams & { error: unknown },
) => void | Response | Error | Promise<void | Response | Error>;

@@ -162,2 +165,3 @@ export type Middleware =

onResponse?: MiddlewareOnResponse;
onError?: MiddlewareOnError;
}

@@ -167,2 +171,8 @@ | {

onResponse: MiddlewareOnResponse;
onError?: MiddlewareOnError;
}
| {
onRequest?: MiddlewareOnRequest;
onResponse?: MiddlewareOnResponse;
onError: MiddlewareOnError;
};

@@ -169,0 +179,0 @@

@@ -127,4 +127,46 @@ // settings & const

// fetch!
let response = await fetch(request);
let response;
try {
response = await fetch(request);
} catch (error) {
let errorAfterMiddleware = error;
// middleware (error)
// execute in reverse-array order (first priority gets last transform)
if (middlewares.length) {
for (let i = middlewares.length - 1; i >= 0; i--) {
const m = middlewares[i];
if (m && typeof m === "object" && typeof m.onError === "function") {
const result = await m.onError({
request,
error: errorAfterMiddleware,
schemaPath,
params,
options,
id,
});
if (result) {
// if error is handled by returning a response, skip remaining middleware
if (result instanceof Response) {
errorAfterMiddleware = undefined;
response = result;
break;
}
if (result instanceof Error) {
errorAfterMiddleware = result;
continue;
}
throw new Error("onError: must return new Response() or instance of Error");
}
}
}
}
// rethrow error if not handled by middleware
if (errorAfterMiddleware) {
throw errorAfterMiddleware;
}
}
// middleware (response)

@@ -217,4 +259,4 @@ // execute in reverse-array order (first priority gets last transform)

}
if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m)) {
throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");
if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) {
throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
}

@@ -221,0 +263,0 @@ middlewares.push(m);

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc