datasquirel/package-shared/functions/api/query-dsql-api.ts
Benjamin Toby ad904622eb Updates
2025-07-05 17:27:26 +01:00

147 lines
4.6 KiB
TypeScript

import path from "path";
import { OutgoingHttpHeaders } from "http";
import {
APIResponseObject,
DataCrudRequestMethods,
DataCrudRequestMethodsLowerCase,
} from "../../types";
import grabHostNames from "../../utils/grab-host-names";
import serializeQuery from "../../utils/serialize-query";
import { RequestOptions } from "https";
type Param<T = { [k: string]: any }> = {
body?: T;
query?: T;
useDefault?: boolean;
path: string;
method?:
| (typeof DataCrudRequestMethods)[number]
| (typeof DataCrudRequestMethodsLowerCase)[number];
apiKey?: string;
};
/**
* # Query DSQL API
*/
export default async function queryDSQLAPI<
T = { [k: string]: any },
P = { [k: string]: any }
>({
body,
query,
useDefault,
path: passedPath,
method,
apiKey,
}: Param<T>): Promise<APIResponseObject<P>> {
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: OutgoingHttpHeaders = {
"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 requestOptions: RequestOptions = {
method: method || "GET",
headers,
port,
hostname: host,
path: finalPath,
};
const httpsRequest = scheme.request(
requestOptions,
/**
* 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));
} catch (error: any) {
resolve({
success: false,
payload: undefined,
msg: `An error occurred while parsing the response`,
error: error.message,
errorData: { requestOptions, grabedHostNames },
} as APIResponseObject);
}
});
response.on("error", (err) => {
resolve({
success: false,
payload: undefined,
msg: `An error occurred on the response`,
error: err.message,
errorData: { requestOptions, grabedHostNames },
} as APIResponseObject);
});
}
);
httpsRequest.on("error", (err) => {
resolve({
success: false,
payload: undefined,
msg: `An error occurred while making the request`,
error: err.message,
errorData: { requestOptions, grabedHostNames },
} as APIResponseObject);
});
if (reqPayload) {
httpsRequest.write(reqPayload);
}
httpsRequest.end();
});
return httpResponse as APIResponseObject<P>;
} catch (error: any) {
return {
success: false,
payload: undefined,
msg: `Request Failed`,
error: error.message,
};
}
}