datasquirel/utils/get-schema.js

85 lines
2.8 KiB
JavaScript
Raw Normal View History

2023-09-21 14:00:04 +00:00
// @ts-check
2023-09-21 16:51:08 +00:00
const http = require("http");
2023-09-21 14:00:04 +00:00
const https = require("https");
2024-11-13 13:13:10 +00:00
const grabHostNames = require("../package-shared/utils/grab-host-names");
2023-09-21 14:00:04 +00:00
/**
* @typedef {Object} GetSchemaReturn
* @property {boolean} success - Did the function run successfully?
2024-10-22 17:32:02 +00:00
* @property {import("../package-shared/types").DSQL_DatabaseSchemaType | import("../package-shared/types").DSQL_TableSchemaType | import("../package-shared/types").DSQL_FieldSchemaType | null} payload - Response payload
2023-09-21 14:00:04 +00:00
*/
/**
2024-10-22 17:17:59 +00:00
* # Get Schema for Database, table, or field *
* @param {import("../package-shared/types").GetSchemaAPIParam} params
2023-09-21 14:00:04 +00:00
*
* @returns { Promise<GetSchemaReturn> } - Return Object
*/
async function getSchema({ key, database, field, table, user_id }) {
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
2023-09-21 16:51:08 +00:00
2023-09-21 14:00:04 +00:00
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
2024-10-22 17:17:59 +00:00
/** @type {import("../package-shared/types").GetSchemaRequestQuery} */
const queryObject = { database, field, table };
let query = Object.keys(queryObject)
// @ts-ignore
.filter((k) => queryObject[k])
// @ts-ignore
.map((k) => `${k}=${queryObject[k]}`)
.join("&");
2024-11-13 13:13:10 +00:00
scheme
2023-09-21 14:00:04 +00:00
.request(
{
method: "GET",
headers: {
"Content-Type": "application/json",
2024-11-15 14:37:53 +00:00
Authorization:
key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
2023-09-21 14:00:04 +00:00
},
2024-11-13 13:13:10 +00:00
port,
hostname: host,
2023-09-21 16:51:08 +00:00
path:
`/api/query/${
user_id || grabedHostNames.user_id
}/get-schema` + (query?.match(/./) ? `?${query}` : ""),
2023-09-21 14:00:04 +00:00
},
/**
* 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);
});
}
)
.end();
});
return httpResponse;
}
module.exports = getSchema;