import stringifyObject from"stringify-object";import{CodeBuilder}from"../../helpers/code-builder";import{addIndentation,getPreserveTransformer,buildUrlExpression,printUrlVariablesDeclarations}from"../../helpers/code-helpers";import{Lang}from"../../helpers/constants";import{normalizeMimeType}from"../../../../utils";import{HTTPSnippet}from"../..";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:"  ",showBoilerplate:!0,level:1},t),{level:h}=p;let c=!1;const m=new CodeBuilder({indentation:p.indent,variablesPrefix:p.variablesPrefix,capitalize:!0,lang:Lang.NODEJS});p.withComments&&addComments(m),p.withImports&&(m.push("import fetch from 'node-fetch';"),m.blank()),p.showBoilerplate&&m.push("async function run() {");const u={method:e.method.toUpperCase()};Object.keys(e.headersObj).length&&(u.headers=e.headersObj);let f=!1;if(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",showBoilerplate:!1,level:1}));m.push(t),m.blank(),u.headers=u.headers||{},u.headers.Authorization="'Bearer ' + oAuth2Data.access_token",f=!0}const b=Object.getOwnPropertyNames(e.queryObj).length;if(b&&m.push(h,`const ${m.var("query")} = new URLSearchParams(${addIndentation(stringifyObject(e.queryObj,{indent:p.indent,inlineCharacterLimit:25}),{level:h,indent:p.indent,firstLine:!1})}).toString();`).blank(),e.postData)switch(normalizeMimeType(e.postData.mimeType)){case MediaTypes.URL_ENCODED:u.body=e.postData.paramsObj?`new URLSearchParams(${m.var("formData")}).toString()`:e.postData.text,e.postData.paramsObj&&m.push(h,`const ${m.var("formData")} = ${addIndentation(stringifyObject(e.postData.paramsObj,{indent:p.indent,inlineCharacterLimit:25}),{level:h,firstLine:!1})};`).blank();break;case MediaTypes.JSON:e.postData.jsonObj&&(u.body=`JSON.stringify(${addIndentation(stringifyObject(e.postData.jsonObj,{indent:p.indent,inlineCharacterLimit:25}),{level:h,firstLine:!1})})`);break;case MediaTypes.MULTIPART:(null===(r=null==u?void 0:u.headers)||void 0===r?void 0:r["Content-Type"])&&(null===(o=u.headers)||void 0===o||delete o["Content-Type"]),p.withImports&&m.unshift("import FormData from 'form-data';"),m.push(h,`const ${m.var("form")} = new FormData();`),e.postData.params.forEach((function(e){e.fileName||e.fileName||e.contentType?e.fileName&&(c=!0,m.blank(),m.push(h,`${m.var("form")}.append('" + param.name + "', fs.createReadStream('" + param.fileName + "'));`)):m.push(h,"form.append('"+e.name+"','"+e.value+"');")})),u.body=m.var("form"),m.blank();break;default:e.postData.text&&(u.body=`\`${addIndentation(e.postData.text,{level:h+1,indent:p.indent,firstLine:!1}).trim()}\``)}if(e.cookies.length){let t="";e.cookies.forEach((function(e){t=t+encodeURIComponent(e.name)+"="+encodeURIComponent(e.value)+"; "})),t=t.trim(),u.headers||(u.headers={}),u.headers.cookie=t}if(e.basicAuth){const{username:t,password:a}=e.basicAuth;u.headers=u.headers||{},u.headers.Authorization=`'Basic ' + Buffer.from('${t}:${a}').toString('base64')`,f=!0}c&&p.withImports&&m.unshift("import fs from 'fs';");const v=u.headers&&u.headers.Accept&&normalizeMimeType(u.headers.Accept)===MediaTypes.JSON||normalizeMimeType(null===(d=e.postData)||void 0===d?void 0:d.mimeType)===MediaTypes.JSON;printUrlVariablesDeclarations(e,m,h);const y=buildUrlExpression(e,m);return m.push(h,`const ${m.var("resp")} = await fetch(`).push(h+1,"`"+y+(b?"?${"+m.var("query")+"}":"")+"`,").push(h+1,addIndentation(stringifyObject(u,{indent:p.indent,inlineCharacterLimit:25,transform:getPreserveTransformer({body:!0,authorizationHeader:f})}),{level:h+1,indent:p.indent,firstLine:!1})).push(h,");").blank(),(null===(l=e.allResponseCodes)||void 0===l?void 0:l.includes("204"))?(m.push(h,"if (resp.status === 204) {").push(h+1,"console.log('success');").push(h,"} else {"),m.push(h+1,`const ${m.var("data")} = await ${m.var("resp")}.${v?"json()":"text()"};`).push(h+1,`console.log(${m.var("data")});`).push(h,"}")):m.push(h,`const ${m.var("data")} = await ${m.var("resp")}.${v?"json()":"text()"};`).push(h,`console.log(${m.var("data")});`),p.showBoilerplate&&m.push("}").blank().push("run();"),m.join().replace(/"fs\.createReadStream\(\\"(.+)\\"\)"/,'fs.createReadStream("$1")')};function addComments(e){e.push("/**"),e.push(" * Requires Node.js >= 14"),e.push(" *"),e.push(' * Requires module "node-fetch" >= 2.6.1'),e.push(" * See here for installation details:"),e.push(" *   https://www.npmjs.com/package/node-fetch"),e.push(" */"),e.blank()}export const info={key:"fetch",title:"Fetch",link:"https://github.com/bitinn/node-fetch",description:"Simplified HTTP node-fetch client"};export default handler;
//# sourceMappingURL=fetch.js.map