@hey-api/client-axios
Advanced tools
Comparing version 0.3.3 to 0.3.4
@@ -33,2 +33,4 @@ import { CreateAxiosDefaults, AxiosStatic, AxiosResponse, AxiosError, AxiosInstance } from 'axios'; | ||
/** | ||
* **This feature works only with the [experimental parser](https://heyapi.dev/openapi-ts/configuration#parser)** | ||
* | ||
* Access token or a function returning access token. The resolved token will | ||
@@ -39,2 +41,4 @@ * be added to request payload as required. | ||
/** | ||
* **This feature works only with the [experimental parser](https://heyapi.dev/openapi-ts/configuration#parser)** | ||
* | ||
* API key or a function returning API key. The resolved key will be added | ||
@@ -86,2 +90,4 @@ * to the request payload as required. | ||
/** | ||
* **This feature works only with the [experimental parser](https://heyapi.dev/openapi-ts/configuration#parser)** | ||
* | ||
* A function validating response data. This is useful if you want to ensure | ||
@@ -88,0 +94,0 @@ * the response conforms to the desired shape, so it can be safely passed to |
@@ -1,7 +0,7 @@ | ||
import U from 'axios'; | ||
import E from 'axios'; | ||
var O=/\{[^{}]+\}/g,d=({allowReserved:t,name:r,value:e})=>{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 `${r}=${t?e:encodeURIComponent(e)}`},j=t=>{switch(t){case"label":return ".";case"matrix":return ";";case"simple":return ",";default:return "&"}},A=t=>{switch(t){case"form":return ",";case"pipeDelimited":return "|";case"spaceDelimited":return "%20";default:return ","}},R=t=>{switch(t){case"label":return ".";case"matrix":return ";";case"simple":return ",";default:return "&"}},b=({allowReserved:t,explode:r,name:e,style:a,value:s})=>{if(!r){let n=(t?s:s.map(c=>encodeURIComponent(c))).join(A(a));switch(a){case"label":return `.${n}`;case"matrix":return `;${e}=${n}`;case"simple":return n;default:return `${e}=${n}`}}let o=j(a),i=s.map(n=>a==="label"||a==="simple"?t?n:encodeURIComponent(n):d({allowReserved:t,name:e,value:n})).join(o);return a==="label"||a==="matrix"?o+i:i},x=({allowReserved:t,explode:r,name:e,style:a,value:s})=>{if(a!=="deepObject"&&!r){let n=[];Object.entries(s).forEach(([u,l])=>{n=[...n,u,t?l:encodeURIComponent(l)];});let c=n.join(",");switch(a){case"form":return `${e}=${c}`;case"label":return `.${c}`;case"matrix":return `;${e}=${c}`;default:return c}}let o=R(a),i=Object.entries(s).map(([n,c])=>d({allowReserved:t,name:a==="deepObject"?`${e}[${n}]`:n,value:c})).join(o);return a==="label"||a==="matrix"?o+i:i},C=({path:t,url:r})=>{let e=r,a=r.match(O);if(a)for(let s of a){let o=!1,i=s.substring(1,s.length-1),n="simple";i.endsWith("*")&&(o=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(i=i.substring(1),n="label"):i.startsWith(";")&&(i=i.substring(1),n="matrix");let c=t[i];if(c==null)continue;if(Array.isArray(c)){e=e.replace(s,b({explode:o,name:i,style:n,value:c}));continue}if(typeof c=="object"){e=e.replace(s,x({explode:o,name:i,style:n,value:c}));continue}if(n==="matrix"){e=e.replace(s,`;${d({name:i,value:c})}`);continue}let u=encodeURIComponent(n==="label"?`.${c}`:c);e=e.replace(s,u);}return e},w=({allowReserved:t,array:r,object:e}={})=>s=>{let o=[];if(s&&typeof s=="object")for(let i in s){let n=s[i];if(n!=null){if(Array.isArray(n)){o=[...o,b({allowReserved:t,explode:!0,name:i,style:"form",value:n,...r})];continue}if(typeof n=="object"){o=[...o,x({allowReserved:t,explode:!0,name:i,style:"deepObject",value:n,...e})];continue}o=[...o,d({allowReserved:t,name:i,value:n})];}}return o.join("&")},P=async(t,r)=>{if(t.fn==="accessToken"){let e=typeof r.accessToken=="function"?await r.accessToken():r.accessToken;return e?`Bearer ${e}`:void 0}if(t.fn==="apiKey")return typeof r.apiKey=="function"?await r.apiKey():r.apiKey},z=async({security:t,...r})=>{for(let e of t){let a=await P(e,r);if(a){e.in==="header"?r.headers[e.name]=a:e.in==="query"&&(r.query||(r.query={}),r.query[e.name]=a);return}}},y=t=>q({path:t.path,query:t.paramsSerializer?void 0:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:w(t.querySerializer),url:t.url}),q=({path:t,query:r,querySerializer:e,url:a})=>{let o=a.startsWith("/")?a:`/${a}`;t&&(o=C({path:t,url:o}));let i=r?e(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(o+=`?${i}`),o},S=(t,r,e)=>{typeof e=="string"||e instanceof Blob?t.append(r,e):t.append(r,JSON.stringify(e));},m=(t,r)=>{let e={...t,...r};return e.headers=p(t.headers,r.headers),e},p=(...t)=>{let r={};for(let e of t){if(!e||typeof e!="object")continue;let a=Object.entries(e);for(let[s,o]of a)if(o===null)delete r[s];else if(Array.isArray(o))for(let i of o)r[s]=[...r[s]??[],i];else o!==void 0&&(r[s]=typeof o=="object"?JSON.stringify(o):o);}return r},T={bodySerializer:t=>{let r=new FormData;return Object.entries(t).forEach(([e,a])=>{a!=null&&(Array.isArray(a)?a.forEach(s=>S(r,e,s)):S(r,e,a));}),r}},k={bodySerializer:t=>JSON.stringify(t)},h=(t,r,e)=>{typeof e=="string"?t.append(r,e):t.append(r,JSON.stringify(e));},$={bodySerializer:t=>{let r=new URLSearchParams;return Object.entries(t).forEach(([e,a])=>{a!=null&&(Array.isArray(a)?a.forEach(s=>h(r,e,s)):h(r,e,a));}),r}},g=(t={})=>({baseURL:"",...t});var V=t=>{let r=m(g(),t),e=U.create(r),a=()=>({...r}),s=i=>(r=m(r,i),e.defaults={...e.defaults,...r,headers:p(e.defaults.headers,r.headers)},a()),o=async i=>{let n={...r,...i,axios:i.axios??r.axios??e,headers:p(r.headers,i.headers)};n.security&&await z({...n,security:n.security}),n.body&&n.bodySerializer&&(n.body=n.bodySerializer(n.body));let c=y(n);try{let u=n.axios,l=await u({...n,data:n.body,headers:n.headers,params:n.paramsSerializer?n.query:void 0,url:c}),{data:f}=l;return n.responseType==="json"&&(n.responseValidator&&await n.responseValidator(f),n.responseTransformer&&(f=await n.responseTransformer(f))),{...l,data:f??{}}}catch(u){let l=u;if(n.throwOnError)throw l;return l.error=l.response?.data??{},l}};return {buildUrl:y,delete:i=>o({...i,method:"delete"}),get:i=>o({...i,method:"get"}),getConfig:a,head:i=>o({...i,method:"head"}),instance:e,options:i=>o({...i,method:"options"}),patch:i=>o({...i,method:"patch"}),post:i=>o({...i,method:"post"}),put:i=>o({...i,method:"put"}),request:o,setConfig:s}}; | ||
var O=/\{[^{}]+\}/g,f=({allowReserved:t,name:r,value:e})=>{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 `${r}=${t?e:encodeURIComponent(e)}`},j=t=>{switch(t){case"label":return ".";case"matrix":return ";";case"simple":return ",";default:return "&"}},w=t=>{switch(t){case"form":return ",";case"pipeDelimited":return "|";case"spaceDelimited":return "%20";default:return ","}},R=t=>{switch(t){case"label":return ".";case"matrix":return ";";case"simple":return ",";default:return "&"}},b=({allowReserved:t,explode:r,name:e,style:a,value:s})=>{if(!r){let i=(t?s:s.map(c=>encodeURIComponent(c))).join(w(a));switch(a){case"label":return `.${i}`;case"matrix":return `;${e}=${i}`;case"simple":return i;default:return `${e}=${i}`}}let o=j(a),n=s.map(i=>a==="label"||a==="simple"?t?i:encodeURIComponent(i):f({allowReserved:t,name:e,value:i})).join(o);return a==="label"||a==="matrix"?o+n:n},x=({allowReserved:t,explode:r,name:e,style:a,value:s})=>{if(a!=="deepObject"&&!r){let i=[];Object.entries(s).forEach(([u,l])=>{i=[...i,u,t?l:encodeURIComponent(l)];});let c=i.join(",");switch(a){case"form":return `${e}=${c}`;case"label":return `.${c}`;case"matrix":return `;${e}=${c}`;default:return c}}let o=R(a),n=Object.entries(s).map(([i,c])=>f({allowReserved:t,name:a==="deepObject"?`${e}[${i}]`:i,value:c})).join(o);return a==="label"||a==="matrix"?o+n:n},A=({path:t,url:r})=>{let e=r,a=r.match(O);if(a)for(let s of a){let o=!1,n=s.substring(1,s.length-1),i="simple";n.endsWith("*")&&(o=!0,n=n.substring(0,n.length-1)),n.startsWith(".")?(n=n.substring(1),i="label"):n.startsWith(";")&&(n=n.substring(1),i="matrix");let c=t[n];if(c==null)continue;if(Array.isArray(c)){e=e.replace(s,b({explode:o,name:n,style:i,value:c}));continue}if(typeof c=="object"){e=e.replace(s,x({explode:o,name:n,style:i,value:c}));continue}if(i==="matrix"){e=e.replace(s,`;${f({name:n,value:c})}`);continue}let u=encodeURIComponent(i==="label"?`.${c}`:c);e=e.replace(s,u);}return e},C=({allowReserved:t,array:r,object:e}={})=>s=>{let o=[];if(s&&typeof s=="object")for(let n in s){let i=s[n];if(i!=null){if(Array.isArray(i)){o=[...o,b({allowReserved:t,explode:!0,name:n,style:"form",value:i,...r})];continue}if(typeof i=="object"){o=[...o,x({allowReserved:t,explode:!0,name:n,style:"deepObject",value:i,...e})];continue}o=[...o,f({allowReserved:t,name:n,value:i})];}}return o.join("&")},P=async(t,r)=>{if(t.fn==="accessToken"){let e=typeof r.accessToken=="function"?await r.accessToken():r.accessToken;return e?`Bearer ${e}`:void 0}if(t.fn==="apiKey")return typeof r.apiKey=="function"?await r.apiKey():r.apiKey},z=async({security:t,...r})=>{for(let e of t){let a=await P(e,r);if(a){e.in==="header"?r.headers[e.name]=a:e.in==="query"&&(r.query||(r.query={}),r.query[e.name]=a);return}}},y=t=>q({path:t.path,query:t.paramsSerializer?void 0:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:C(t.querySerializer),url:t.url}),q=({path:t,query:r,querySerializer:e,url:a})=>{let o=a.startsWith("/")?a:`/${a}`;t&&(o=A({path:t,url:o}));let n=r?e(r):"";return n.startsWith("?")&&(n=n.substring(1)),n&&(o+=`?${n}`),o},S=(t,r,e)=>{typeof e=="string"||e instanceof Blob?t.append(r,e):t.append(r,JSON.stringify(e));},m=(t,r)=>{let e={...t,...r};return e.headers=p(t.headers,r.headers),e},k=["common","delete","get","head","patch","post","put"],p=(...t)=>{let r={};for(let e of t){if(!e||typeof e!="object")continue;let a=Object.entries(e);for(let[s,o]of a)if(k.includes(s)&&typeof o=="object")r[s]={...r[s],...o};else if(o===null)delete r[s];else if(Array.isArray(o))for(let n of o)r[s]=[...r[s]??[],n];else o!==void 0&&(r[s]=typeof o=="object"?JSON.stringify(o):o);}return r},T={bodySerializer:t=>{let r=new FormData;return Object.entries(t).forEach(([e,a])=>{a!=null&&(Array.isArray(a)?a.forEach(s=>S(r,e,s)):S(r,e,a));}),r}},$={bodySerializer:t=>JSON.stringify(t)},h=(t,r,e)=>{typeof e=="string"?t.append(r,e):t.append(r,JSON.stringify(e));},U={bodySerializer:t=>{let r=new URLSearchParams;return Object.entries(t).forEach(([e,a])=>{a!=null&&(Array.isArray(a)?a.forEach(s=>h(r,e,s)):h(r,e,a));}),r}},g=(t={})=>({baseURL:"",...t});var K=t=>{let r=m(g(),t),e=E.create(r),a=()=>({...r}),s=n=>(r=m(r,n),e.defaults={...e.defaults,...r,headers:p(e.defaults.headers,r.headers)},a()),o=async n=>{let i={...r,...n,axios:n.axios??r.axios??e,headers:p(r.headers,n.headers)};i.security&&await z({...i,security:i.security}),i.body&&i.bodySerializer&&(i.body=i.bodySerializer(i.body));let c=y(i);try{let u=i.axios,l=await u({...i,data:i.body,headers:i.headers,params:i.paramsSerializer?i.query:void 0,url:c}),{data:d}=l;return i.responseType==="json"&&(i.responseValidator&&await i.responseValidator(d),i.responseTransformer&&(d=await i.responseTransformer(d))),{...l,data:d??{}}}catch(u){let l=u;if(i.throwOnError)throw l;return l.error=l.response?.data??{},l}};return {buildUrl:y,delete:n=>o({...n,method:"delete"}),get:n=>o({...n,method:"get"}),getConfig:a,head:n=>o({...n,method:"head"}),instance:e,options:n=>o({...n,method:"options"}),patch:n=>o({...n,method:"patch"}),post:n=>o({...n,method:"post"}),put:n=>o({...n,method:"put"}),request:o,setConfig:s}}; | ||
export { V as createClient, g as createConfig, T as formDataBodySerializer, k as jsonBodySerializer, $ as urlSearchParamsBodySerializer }; | ||
export { K as createClient, g as createConfig, T as formDataBodySerializer, $ as jsonBodySerializer, U as urlSearchParamsBodySerializer }; | ||
//# sourceMappingURL=index.js.map | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@hey-api/client-axios", | ||
"version": "0.3.3", | ||
"version": "0.3.4", | ||
"description": "π Axios client for `@hey-api/openapi-ts` codegen.", | ||
@@ -5,0 +5,0 @@ "homepage": "https://heyapi.dev/", |
@@ -23,3 +23,3 @@ <div align="center"> | ||
## Sponsoring | ||
## Sponsors | ||
@@ -30,3 +30,3 @@ Love Hey API? Become our [sponsor](https://github.com/sponsors/hey-api). | ||
<a href="https://kutt.it/pkEZyc" target="_blank"> | ||
<img alt="Stainless logo" height="50" src="https://heyapi.dev/images/stainless-logo-wordmark-480w.png" /> | ||
<img alt="Stainless logo" height="50" src="https://heyapi.dev/images/stainless-logo-wordmark-480w.jpeg" /> | ||
</a> | ||
@@ -41,2 +41,2 @@ </p> | ||
[OpenAPI Typescript Codegen](https://heyapi.dev/openapi-ts/migrating.html#openapi-typescript-codegen). | ||
[OpenAPI Typescript Codegen](https://heyapi.dev/openapi-ts/migrating.html#openapi-typescript-codegen) |
import { describe, expect, it, vi } from 'vitest'; | ||
import { getAuthToken, setAuthParams } from '../utils'; | ||
import { | ||
axiosHeadersKeywords, | ||
getAuthToken, | ||
mergeHeaders, | ||
setAuthParams, | ||
} from '../utils'; | ||
@@ -73,2 +78,26 @@ describe('getAuthToken', () => { | ||
describe('mergeHeaders', () => { | ||
it.each(axiosHeadersKeywords)( | ||
'handles "%s" Axios special keyword', | ||
(keyword) => { | ||
const headers = mergeHeaders( | ||
{ | ||
foo: 'foo', | ||
}, | ||
{ | ||
[keyword]: { | ||
foo: 'foo', | ||
}, | ||
}, | ||
); | ||
expect(headers).toEqual({ | ||
foo: 'foo', | ||
[keyword]: { | ||
foo: 'foo', | ||
}, | ||
}); | ||
}, | ||
); | ||
}); | ||
describe('setAuthParams', () => { | ||
@@ -75,0 +104,0 @@ it('sets access token in headers', async () => { |
@@ -20,2 +20,4 @@ import type { | ||
/** | ||
* **This feature works only with the [experimental parser](https://heyapi.dev/openapi-ts/configuration#parser)** | ||
* | ||
* Access token or a function returning access token. The resolved token will | ||
@@ -26,2 +28,4 @@ * be added to request payload as required. | ||
/** | ||
* **This feature works only with the [experimental parser](https://heyapi.dev/openapi-ts/configuration#parser)** | ||
* | ||
* API key or a function returning API key. The resolved key will be added | ||
@@ -93,2 +97,4 @@ * to the request payload as required. | ||
/** | ||
* **This feature works only with the [experimental parser](https://heyapi.dev/openapi-ts/configuration#parser)** | ||
* | ||
* A function validating response data. This is useful if you want to ensure | ||
@@ -95,0 +101,0 @@ * the response conforms to the desired shape, so it can be safely passed to |
@@ -426,2 +426,15 @@ import type { Client, Config, RequestOptions, Security } from './types'; | ||
/** | ||
* Special Axios headers keywords allowing to set headers by request method. | ||
*/ | ||
export const axiosHeadersKeywords = [ | ||
'common', | ||
'delete', | ||
'get', | ||
'head', | ||
'patch', | ||
'post', | ||
'put', | ||
] as const; | ||
export const mergeHeaders = ( | ||
@@ -439,3 +452,13 @@ ...headers: Array<Required<Config>['headers'] | undefined> | ||
for (const [key, value] of iterator) { | ||
if (value === null) { | ||
if ( | ||
axiosHeadersKeywords.includes( | ||
key as (typeof axiosHeadersKeywords)[number], | ||
) && | ||
typeof value === 'object' | ||
) { | ||
mergedHeaders[key] = { | ||
...(mergedHeaders[key] as Record<any, unknown>), | ||
...value, | ||
}; | ||
} else if (value === null) { | ||
delete mergedHeaders[key]; | ||
@@ -442,0 +465,0 @@ } else if (Array.isArray(value)) { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
115496
1221