74 lines
2.4 KiB
JavaScript
74 lines
2.4 KiB
JavaScript
import path from "path";
|
|
import grabHostNames from "../../utils/grab-host-names";
|
|
import serializeQuery from "../../utils/serialize-query";
|
|
/**
|
|
* # Query DSQL API
|
|
*/
|
|
export default async function queryDSQLAPI({ body, query, useDefault, path: passedPath, method, apiKey, }) {
|
|
const grabedHostNames = grabHostNames({ useDefault });
|
|
const { host, port, scheme } = grabedHostNames;
|
|
try {
|
|
/**
|
|
* Make https request
|
|
*
|
|
* @description make a request to datasquirel.com
|
|
*/
|
|
const httpResponse = await new Promise((resolve, reject) => {
|
|
const reqPayload = body ? JSON.stringify(body) : undefined;
|
|
let headers = {
|
|
"Content-Type": "application/json",
|
|
Authorization: apiKey ||
|
|
(!method || method == "GET" || method == "get"
|
|
? process.env.DSQL_READ_ONLY_API_KEY
|
|
: undefined) ||
|
|
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
|
process.env.DSQL_API_KEY,
|
|
};
|
|
if (reqPayload) {
|
|
headers["Content-Length"] = Buffer.from(reqPayload).length;
|
|
}
|
|
let finalPath = path.join("/", passedPath);
|
|
if (query) {
|
|
const queryString = serializeQuery(query);
|
|
finalPath += `${queryString}`;
|
|
}
|
|
const httpsRequest = scheme.request({
|
|
method: method || "GET",
|
|
headers,
|
|
port,
|
|
hostname: host,
|
|
path: finalPath,
|
|
},
|
|
/**
|
|
* Callback Function
|
|
*
|
|
* @description https request callback
|
|
*/
|
|
(response) => {
|
|
var str = "";
|
|
response.on("data", function (chunk) {
|
|
str += chunk;
|
|
});
|
|
response.on("end", function () {
|
|
resolve(JSON.parse(str));
|
|
});
|
|
response.on("error", (err) => {
|
|
reject(err);
|
|
});
|
|
});
|
|
if (reqPayload) {
|
|
httpsRequest.write(reqPayload);
|
|
}
|
|
httpsRequest.end();
|
|
});
|
|
return httpResponse;
|
|
}
|
|
catch (error) {
|
|
return {
|
|
success: false,
|
|
payload: undefined,
|
|
msg: error.message,
|
|
};
|
|
}
|
|
}
|