128 lines
3.5 KiB
TypeScript
128 lines
3.5 KiB
TypeScript
import https from "node:https";
|
|
import grabHostNames from "../utils/grab-host-names";
|
|
import serializeQuery from "../utils/serialize-query";
|
|
import { APIResponseObject, DsqlCrudQueryObject } from "../types";
|
|
import debugLog from "../utils/logging/debug-log";
|
|
import dsqlCrud from "../utils/data-fetching/crud";
|
|
import grabAPIKey from "../utils/grab-api-key";
|
|
|
|
type Param<T extends { [k: string]: any } = { [k: string]: any }> = {
|
|
key?: string;
|
|
database: string;
|
|
query: DsqlCrudQueryObject<T>;
|
|
table?: string;
|
|
debug?: boolean;
|
|
useLocal?: boolean;
|
|
apiVersion?: string;
|
|
};
|
|
|
|
export type ApiGetParams = Param;
|
|
|
|
/**
|
|
* # Make a get request to Datasquirel API
|
|
*/
|
|
export default async function get<
|
|
T extends { [k: string]: any } = { [k: string]: any },
|
|
R extends any = any
|
|
>({
|
|
key,
|
|
database,
|
|
query,
|
|
table,
|
|
debug,
|
|
useLocal,
|
|
apiVersion = "v1",
|
|
}: Param<T>): Promise<APIResponseObject<R>> {
|
|
const grabedHostNames = grabHostNames();
|
|
const { host, port, scheme } = grabedHostNames;
|
|
|
|
function debugFn(log: any, label?: string) {
|
|
debugLog({ log, addTime: true, title: "apiGet", label });
|
|
}
|
|
|
|
/**
|
|
* Check for local DB settings
|
|
*
|
|
* @description Look for local db settings in `.env` file and by pass the http request if available
|
|
*/
|
|
const { DSQL_DB_NAME } = process.env;
|
|
|
|
if (useLocal) {
|
|
const result = await dsqlCrud({
|
|
action: "get",
|
|
table: table || "",
|
|
dbFullName: database,
|
|
query,
|
|
});
|
|
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* Make https request
|
|
*
|
|
* @description make a request to datasquirel.com
|
|
*/
|
|
const httpResponse = await new Promise((resolve, reject) => {
|
|
const queryString = serializeQuery(query);
|
|
|
|
if (debug) {
|
|
debugFn(queryString, "queryString");
|
|
}
|
|
|
|
let path = `/api/${apiVersion}/crud/${database}/${table}`;
|
|
|
|
if (debug) {
|
|
debugFn(path, "path");
|
|
}
|
|
|
|
const requestObject: https.RequestOptions = {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: grabAPIKey(key),
|
|
},
|
|
port,
|
|
hostname: host,
|
|
path,
|
|
};
|
|
|
|
scheme
|
|
.request(
|
|
requestObject,
|
|
|
|
/**
|
|
* Callback Function
|
|
*
|
|
* @description https request callback
|
|
*/
|
|
(response) => {
|
|
var str = "";
|
|
|
|
response.on("data", function (chunk) {
|
|
str += chunk;
|
|
});
|
|
|
|
response.on("end", function () {
|
|
try {
|
|
resolve(JSON.parse(str) as APIResponseObject);
|
|
} catch (error: any) {
|
|
reject({
|
|
error: error.message,
|
|
result: str,
|
|
});
|
|
}
|
|
});
|
|
|
|
response.on("error", (err) => {
|
|
console.log("DSQL get Error,", err.message);
|
|
resolve(null);
|
|
});
|
|
}
|
|
)
|
|
.end();
|
|
});
|
|
|
|
return httpResponse as APIResponseObject<R>;
|
|
}
|