Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTTP Function Refactor #641

Open
wants to merge 10 commits into
base: v6
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/core/interpreter.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const Interpreter = async (client, message, args, command, _db, returnCode = fal
//defining vars//
let code = command.code?.replaceAll("\\]", "#LEFT#").split("\\[").join("#RIGHT#").replaceAll("\\,", "#COMMA#").replaceAll("\\;", "#SEMI#");

let [randoms, timezone, letVars, object, disableMentions, array, arrays, reactions, channel, author, guild, mentions, member, msg] = [
let [randoms, timezone, letVars, object, disableMentions, array, arrays, reactions, channel, author, guild, mentions, member, msg, requests] = [
data.randoms || {},
"UTC",
data.vars || {},
Expand All @@ -64,7 +64,8 @@ const Interpreter = async (client, message, args, command, _db, returnCode = fal
message.guild,
message.mentions,
message.member,
message
message,
data.requests || {}
];
let errorOccurred;
let embeds;
Expand Down Expand Up @@ -226,6 +227,7 @@ const Interpreter = async (client, message, args, command, _db, returnCode = fal
channel: channel,
member: member,
mentions: mentions,
requests,
unpack() {
const last = code.split(this.func.replace("[", "")).length - 1;
const sliced = code.split(this.func.replace("[", ""))[last];
Expand Down Expand Up @@ -296,6 +298,7 @@ const Interpreter = async (client, message, args, command, _db, returnCode = fal
channel: channel,
member: member,
mentions: mentions, //cleanup (ignore)
requests,
unpack() {
const last = code.split(func.replace("[", "")).length - 1;
const sliced = code.split(func.replace("[", ""))[last];
Expand Down Expand Up @@ -448,6 +451,9 @@ const Interpreter = async (client, message, args, command, _db, returnCode = fal
if (FuncData?.arrays) {
arrays = FuncData?.arrays;
}
if (FuncData?.requests) {
requests = FuncData.requests;
}
}

const ended = (performance.now() - start).toFixed(3);
Expand Down Expand Up @@ -561,4 +567,4 @@ function unpack(code, func) {
const last = code.split(func.replace("[", "")).length - 1;
const sliced = code.split(func.replace("[", ""))[last];
return sliced.after();
}
}
20 changes: 20 additions & 0 deletions src/functions/httpClearOptions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @param {import("..").Data} d
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
const name = data.inside.splits[0] || "res";

if (!d.requests[name]) {
return d.aoiError.fnError(d, "custom", {
inside: data.inside
}, `Invalid request name "${name}"!`)
}

d.requests[name] = {};

return {
code: d.util.setCode(data),
requests: d.requests
}
}
22 changes: 22 additions & 0 deletions src/functions/httpGetHeader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* @param {import("..").Data} d
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
if (data.err) return d.error(data.err);

let [headerName, name = "res"] = data.inside.splits;

if (!d.requests[name]) {
return d.aoiError.fnError(d, "custom", {
inside: data.inside
}, `Invalid request name "${name}"!`)
}

data.result = d.requests[name].headers[headerName.addBrackets()]

return {
code: d.util.setCode(data),
requests: d.requests
}
}
20 changes: 20 additions & 0 deletions src/functions/httpOk.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @param {import("..").Data} d
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
const name = data.inside.splits[0] || "res";

if (!d.requests[name]) {
return d.aoiError.fnError(d, "custom", {
inside: data.inside
}, `Invalid request name "${name}"!`)
}

data.result = d.requests[name].ok;

return {
code: d.util.setCode(data),
requests: d.requests
}
}
20 changes: 20 additions & 0 deletions src/functions/httpRedirected.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @param {import("..").Data} d
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
const name = data.inside.splits[0] || "res";

if (!d.requests[name]) {
return d.aoiError.fnError(d, "custom", {
inside: data.inside
}, `Invalid request name "${name}"!`)
}

data.result = d.requests[name].redirected;

return {
code: d.util.setCode(data),
requests: d.requests
}
}
26 changes: 26 additions & 0 deletions src/functions/httpRemoveHeader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @param {import("..").Data} d
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
if (data.err) return d.error(data.err);

let [headerName, name = "res"] = data.inside.splits;

if (!d.requests[name]) {
return d.aoiError.fnError(d, "custom", {
inside: data.inside
}, `Invalid request name "${name}"!`)
}

if (!headerName) return d.aoiError.fnError(d, "custom", {
inside: data.inside
}, "Missing header name!");

delete d.data.http?.headers[name];

return {
code: d.util.setCode(data),
requests: d.requests
}
}
111 changes: 48 additions & 63 deletions src/functions/httpRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,77 +5,62 @@ const { Agent, fetch } = require('undici');
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
if (data.err) return d.error(data.err);


let [
url,
method = 'get',
body = '',
property,
error = 'default',
...header
method = "get",
body = "",
encoding = "utf-8",
name = "res"
] = data.inside.splits;

body = body?.trim() === '' ? undefined : body;

let headers = {};
if (header.length === 1) {
try {
headers = JSON.parse(header);
} catch (e) {
header.forEach((x) => {
const split = x.split(':');
headers[split[0]] = split[1];
});
}
} else if (header.length > 1) {
header.forEach((x) => {
const split = x.split(':');
headers[split[0]] = split[1];
});
}
// Creating the aoijs response object.
d.requests[name] ??= {};

body = body !== "" ? body.trim() : d.requests[name].body !== undefined ? d.requests[name].body : body;

try {
const response = await fetch(url.addBrackets(), {
method,
headers,
body,
agent: new Agent(),
});
// Getting the user-defined headers.
const headers = {};
if (d.requests[name].headers) {
Object.assign(headers, d.requests[name].headers);
}

const responseBody = await response.text();
const contentType = response.headers.get("content-type")?.split(/;/)[0];
// Making the request.
const response = await fetch(url.addBrackets(), {
body: body === "" ? undefined : body.addBrackets(),
headers,
method,
credentials: d.requests[name]?.credentials
});

if (property && /content(-|\s)?type/gi.test(property)) {
data.result = contentType;
} else if (property && contentType.includes("json")) {
data.result = eval(`JSON.parse(responseBody)?.${property}`)
} else {
data.result = responseBody;
}
} catch (err) {
console.error(err);
if (error === 'default') {
return d.aoiError.makeMessageError(
d.client,
d.channel,
{ content: err },
{},
d
);
} else {
const parsedError = await d.util.errorParser(error, d);
return d.aoiError.makeMessageError(
d.client,
d.channel,
parsedError.data ?? parsedError,
parsedError.options,
d
);
}
// Defining response headers.
(d.requests[name]??={})["headers"] = {};
for (const [headerName, value] of response.headers.entries()) {
d.requests[name].headers[headerName] = value;
}

// Get the response content type.
const contentType = response.headers.get("content-type")?.split(/;/)[0];

// Defining response content type.
d.requests[name].statusCode = response.status;

// Additional response data.
d.requests[name].redirected = response.redirected;
d.requests[name].ok = response.ok;

// Saving the result.
if (contentType.match(/application\/json/)) {
d.requests[name].result = await response.json()
} else if (contentType.match(/image\//)) {
d.requests[name].result = await response.arrayBuffer()
.then(a => Buffer.from(a).toString(encoding));
} else {
d.requests[name].result = await response.text()
}

return {
code: d.util.setCode(data),
};
};
requests: d.requests
}
}
39 changes: 39 additions & 0 deletions src/functions/httpResult.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* @param {import("..").Data} d
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
let [name = "res", ...properties] = data.inside.splits;

if (!d.requests[name]) {
return d.aoiError.fnError(d, "custom", {
inside: data.inside
}, `Invalid request name "${name}"!`)
}

if (!properties.length) {
data.result = typeof d.requests[name].result === "object"
? JSON.stringify(d.requests[name].result)
: d.requests[name].result;
} else if (isObject) {
let response = d.requests[name].result;
for (const property of properties) {
if (!Object.prototype.hasOwnProperty.call(response, property)) {
return d.aoiError.fnError(d, "custom", {
inside: data.inside
}, `Invalid property "${property}" in HTTP result!`)
}

response = response?.[property];
}

data.result = typeof response !== "string"
? JSON.stringify(response)
: String(response);
}

return {
code: d.util.setCode(data),
requests: d.requests
}
}
16 changes: 16 additions & 0 deletions src/functions/httpSetBody.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* @param {import("..").Data} d
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
if (data.err) return d.error(data.err);

let [body, name = "res"] = data.inside.splits;

(d.requests[name] ??= {}).body = body;

return {
code: d.util.setCode(data),
requests: d.requests
}
}
16 changes: 16 additions & 0 deletions src/functions/httpSetCredentials.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* @param {import("..").Data} d
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
if (data.err) return d.error(data.err);

let [credentialsText, name = "res"] = data.inside.splits;

(d.requests[name] ??= {}).credentials = credentialsText;

return {
code: d.util.setCode(data),
requests: d.requests
}
}
16 changes: 16 additions & 0 deletions src/functions/httpSetHeader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* @param {import("..").Data} d
*/
module.exports = async (d) => {
const data = d.util.aoiFunc(d);
if (data.err) return d.error(data.err);

let [headerName, headerValue, name = "res"] = data.inside.splits;

((d.requests[name] ??= {})["headers"] ??= {})[headerName] = headerValue;

return {
code: d.util.setCode(data),
requests: d.requests
}
}
Loading