import stringifyObject from"stringify-object";import{CodeBuilder}from"../../helpers/code-builder";import{addIndentation,getPreserveTransformer,buildUrlExpression,printUrlVariablesDeclarations}from"../../helpers/code-helpers";import{normalizeMimeType}from"../../../../utils";import{HTTPSnippet}from"../..";import{Lang}from"../../helpers/constants";import{MediaTypes}from"../../../../../constants";const handler=function(e,t,{target:a,client:n}){var s,i,r,o,d,l;const p=Object.assign({indent:"  ",credentials:null},t),c=new CodeBuilder({indentation:p.indent,variablesPrefix:p.variablesPrefix,capitalize:!0,lang:Lang.JAVASCRIPT}),h={method:e.method.toUpperCase()};Object.keys(e.headersObj).length&&(h.headers=e.headersObj);let u=!1;if(p.withComments&&addComments(c),null===(s=e.securityOAuth2ExtraCalls)||void 0===s?void 0:s.length){const t=new HTTPSnippet(null===(i=e.securityOAuth2ExtraCalls)||void 0===i?void 0:i[0]).convert(a,n,Object.assign(Object.assign({},p),{withImports:!1,withComments:!1,variablesPrefix:"oAuth2"}));c.push(t),c.blank(),h.headers=h.headers||{},h.headers.Authorization="'Bearer ' + oAuth2Data.access_token",u=!0}null!==p.credentials&&(h.credentials=p.credentials);const m=Object.getOwnPropertyNames(e.queryObj).length;if(m&&c.push(`const ${c.var("query")} = new URLSearchParams(${stringifyObject(e.queryObj,{indent:p.indent,inlineCharacterLimit:25})}).toString();`).blank(),e.postData)switch(normalizeMimeType(e.postData.mimeType)){case MediaTypes.URL_ENCODED:h.body=e.postData.paramsObj?`new URLSearchParams(${c.var("formData")}).toString()`:e.postData.text,e.postData.paramsObj&&c.push(`const ${c.var("formData")} = ${addIndentation(stringifyObject(e.postData.paramsObj,{indent:p.indent,inlineCharacterLimit:25}),{level:0,firstLine:!1})};`).blank();break;case MediaTypes.JSON:e.postData.jsonObj&&(h.body=`JSON.stringify(${addIndentation(stringifyObject(e.postData.jsonObj,{indent:p.indent,inlineCharacterLimit:25}),{level:1,firstLine:!1})})`);break;case MediaTypes.MULTIPART:c.push(`const ${c.var("form")} = new FormData();`),(null===(r=null==h?void 0:h.headers)||void 0===r?void 0:r["Content-Type"])&&(null===(o=h.headers)||void 0===o||delete o["Content-Type"]),e.postData.params.forEach((function(e){c.push(`${c.var("form")}.append(%s, %s);`,JSON.stringify(e.name),JSON.stringify(e.value||e.fileName||""))})),h.body=c.var("form"),c.blank();break;default:e.postData.text&&(h.body=`\`${addIndentation(e.postData.text,{level:2,indent:p.indent,firstLine:!1}).trim()}\``)}const b=h.headers&&h.headers.Accept&&normalizeMimeType(h.headers.Accept)===MediaTypes.JSON||normalizeMimeType(null===(d=e.postData)||void 0===d?void 0:d.mimeType)===MediaTypes.JSON;if(e.basicAuth){const{username:t,password:a}=e.basicAuth;h.headers=h.headers||{},h.headers.Authorization=`'Basic ' + btoa('${t}:${a}')`,u=!0}printUrlVariablesDeclarations(e,c);const f=buildUrlExpression(e,c);return c.push(`const ${c.var("resp")} = await fetch(`).push(1,"`"+f+(m?"?${"+c.var("query")+"}":"")+"`,").push(addIndentation(stringifyObject(h,{indent:p.indent,inlineCharacterLimit:25,transform:getPreserveTransformer({body:!0,authorizationHeader:u})}),{level:1,indent:p.indent})).push(");").blank(),(null===(l=e.allResponseCodes)||void 0===l?void 0:l.includes("204"))?(c.push("if (resp.status === 204) {").push(1,"console.log('success');").push("} else {"),c.push(1,`const ${c.var("data")} = await ${c.var("resp")}.${b?"json()":"text()"};`).push(1,`console.log(${c.var("data")});`).push("}")):c.push(`const ${c.var("data")} = await ${c.var("resp")}.${b?"json()":"text()"};`).push(`console.log(${c.var("data")});`),c.join()};function addComments(e){e.push("/**"),e.push(" * Requires ES8-compatible browser: https://caniuse.com/async-functions"),e.push(" */"),e.blank()}export const info={key:"fetch",title:"fetch",link:"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",description:"Perform asynchronous HTTP requests with the Fetch API"};export default handler;
//# sourceMappingURL=fetch.js.map