datasquirel/engine/schema-to-typedef.ts
Benjamin Toby 700a704abd Updates
2025-08-13 11:16:28 +01:00

127 lines
3.3 KiB
JavaScript

#! /usr/bin/env node
import fs, { readFileSync } from "fs";
import datasquirel from "..";
import dbSchemaToType from "../package-shared/functions/dsql/db-schema-to-type";
import path from "path";
import debugLog from "../package-shared/utils/logging/debug-log";
import { AppNames } from "../package-shared/dict/app-names";
import { APIConnectionOptions } from "../package-shared/types";
type Config = {
database?: string;
outDir?: string;
outFile?: string;
apiConnectionConfig?: APIConnectionOptions;
debug?: boolean;
};
const configFileName = AppNames["SchemaToTypeDefConfigFileName"];
const configFilePath = path.join(process.cwd(), configFileName);
if (!fs.existsSync(configFilePath)) {
debugLog({
log: `Config File doesn't exist. Please add a '${AppNames["SchemaToTypeDefConfigFileName"]}' in the working directory with relevant configurations.`,
addTime: true,
type: "error",
});
process.exit(1);
}
const config: Config = JSON.parse(
readFileSync(path.join(process.cwd(), configFileName), "utf-8")
);
if (!config.database) {
debugLog({
log: `Config File needs a 'database' value.`,
addTime: true,
type: "error",
});
process.exit(1);
}
if (!config.outDir && !config.outFile) {
debugLog({
log: `Config File needs a 'outDir' or 'outFile' value.`,
addTime: true,
type: "error",
});
process.exit(1);
}
if (!config.apiConnectionConfig) {
debugLog({
log: `Config File needs a 'apiConnectionConfig' value. This value needs an 'apiKey' value.`,
addTime: true,
type: "error",
});
process.exit(1);
}
if (!config.apiConnectionConfig.apiKey) {
debugLog({
log: `Config value 'apiConnectionConfig' needs an 'apiKey' value.`,
addTime: true,
type: "error",
});
process.exit(1);
}
(async () => {
try {
if (config.debug) {
debugLog({
log: config,
label: "Config",
addTime: true,
});
}
const schemaRes = await datasquirel.api.schema.get({
dbName: config.database || "",
apiConnectionConfig: config.apiConnectionConfig,
});
const dbSchema = schemaRes.payload;
if (config.debug) {
debugLog({
log: schemaRes,
label: "schema",
addTime: true,
});
}
if (!dbSchema) throw new Error("No schema found");
const definitions = dbSchemaToType({ dbSchema });
const finalOutfile = path.resolve(
process.cwd(),
config.outDir ? config.outDir + "/dsql.ts" : config.outFile || ""
);
const ourfileDir = path.dirname(finalOutfile);
if (!fs.existsSync(ourfileDir)) {
fs.mkdirSync(ourfileDir, { recursive: true });
}
fs.writeFileSync(
finalOutfile,
definitions?.join("\n\n") || "",
"utf-8"
);
} catch (error: any) {
debugLog({
log: error.message,
label: "Error",
title: "Schema to Typedef",
addTime: true,
type: "error",
});
process.exit(1);
}
})();