export default async function handler(request: Request) {
if (request.method !== "POST") {
return Response.json({ message: "This val responds to POST requests." }, { status: 400 });
}
try {
const body = await request.text();
console.log("request.text", body);
let result = generateSnippet(body);
return new Response(result);
} catch (e) {
console.log(e);
return Response.json({ message: "The body of this request was not JSON-encoded." }, {
status: 400,
});
}
}
function writeLog(text = "Hello World") {
console.log(text);
}
function generateSnippet(inputText) {
console.clear();
if (typeof inputText === "object") throw "Input is an object so no go!";
try {
inputText = JSON.parse(inputText);
} catch (error) {
let msg = "ERROR: generateSnippet - JSON Parse error from input!";
console.error(msg);
return msg;
throw msg;
}
let sections = Object.keys(inputText);
let urlCode = "";
let headerCode = "";
let authCode = "";
let methodCode = "";
let bodyCode = "";
let triggerCode = "";
sections.forEach((section) => {
if (section.toLowerCase() === "url") { urlCode = genUrlCode(inputText[section]); }
if (section.toLowerCase() === "header") { headerCode = genHeaderCode(inputText[section]); }
if (section.toLowerCase() === "auth") { authCode = genAuthCode(inputText[section]); }
if (section.toLowerCase() === "method") { methodCode = genMethodCode(inputText[section]); }
if (section.toLowerCase() === "body") { bodyCode = genBodyCode(inputText[section]); }
});
triggerCode = genTriggerCode();
if (!headerCode) {
headerCode = genHeaderCode({});
}
let sectionVariables = [urlCode, headerCode, authCode, methodCode, bodyCode];
for (let codeResult in sectionVariables) {
if (sectionVariables[codeResult].startsWith("ERROR")) {
return sectionVariables[codeResult];
}
}
let finalCode = "//\n// Url code\n//\n";
finalCode += urlCode;
finalCode += "\n\n//\n// Header code\n//\n";
finalCode += headerCode;
if (authCode) {
finalCode += "\n\n//\n// Auth code\n//\n";
finalCode += authCode;
}
finalCode += "\n\n//\n// Method code\n//\n";
finalCode += methodCode;
finalCode += "\n\n//\n// Body code\n//\n";
finalCode += bodyCode;
finalCode += "\n\n//\n// Trigger code\n//\n";
finalCode += triggerCode;
return finalCode;
}
function genUrlCode(jsonObj) {
let url = getUrl(jsonObj);
let queryParamsArray = getQueryString(jsonObj);
let urlCode = "ASSIGN RestProxy_Url = \"" + url + "\"";
if (queryParamsArray) {
urlCode += "\n\n// Url Query Params";
urlCode += "\nASSIGN RestProxy_UrlQueryParams = \"?\"";