datasquirel/utils/get-schema.ts

99 lines
2.9 KiB
TypeScript
Raw Normal View History

2023-09-21 14:00:04 +00:00
// @ts-check
2025-01-10 19:10:28 +00:00
import grabHostNames from "../package-shared/utils/grab-host-names";
import {
DSQL_DatabaseSchemaType,
DSQL_FieldSchemaType,
DSQL_TableSchemaType,
GetSchemaAPIParam,
GetSchemaRequestQuery,
} from "../package-shared/types";
2023-09-21 14:00:04 +00:00
2025-01-10 19:10:28 +00:00
type GetSchemaReturn = {
success: boolean;
payload?:
| DSQL_DatabaseSchemaType
| DSQL_TableSchemaType
| DSQL_FieldSchemaType
| null;
};
2023-09-21 14:00:04 +00:00
/**
2024-10-22 17:17:59 +00:00
* # Get Schema for Database, table, or field *
2023-09-21 14:00:04 +00:00
*/
2025-01-10 19:10:28 +00:00
export default async function getSchema({
key,
database,
field,
table,
user_id,
}: GetSchemaAPIParam): Promise<GetSchemaReturn> {
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) => {
2025-01-10 19:10:28 +00:00
const queryObject: GetSchemaRequestQuery = { database, field, table };
2024-10-22 17:17:59 +00:00
let query = Object.keys(queryObject)
2025-01-10 19:10:28 +00:00
.filter((k) => queryObject[k as keyof GetSchemaRequestQuery])
.map((k) => `${k}=${queryObject[k as keyof GetSchemaRequestQuery]}`)
2024-10-22 17:17:59 +00:00
.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 () {
2025-01-10 19:10:28 +00:00
resolve(
JSON.parse(str) as
| DSQL_DatabaseSchemaType
| DSQL_TableSchemaType
| DSQL_FieldSchemaType
);
2023-09-21 14:00:04 +00:00
});
response.on("error", (err) => {
2025-01-10 19:10:28 +00:00
resolve(null);
2023-09-21 14:00:04 +00:00
});
}
)
.end();
});
2025-01-10 19:10:28 +00:00
return {
success: true,
payload: httpResponse as any,
};
2023-09-21 14:00:04 +00:00
}