datasquirel/engine/schema-to-typedef.ts
Benjamin Toby c24afca519 Updates
2025-04-17 11:11:29 +01:00

104 lines
3.0 KiB
JavaScript

#! /usr/bin/env node
import inquirer from "inquirer";
import fs from "fs";
import datasquirel from "..";
import { parseArgs } from "util";
import { DSQL_DatabaseSchemaType } from "../package-shared/types";
import dbSchemaToType from "../package-shared/functions/dsql/db-schema-to-type";
import path from "path";
import debugLog from "../package-shared/utils/logging/debug-log";
const args = parseArgs({
args: process.argv,
options: {
apiKey: {
type: "string",
default: process.env.DSQL_FULL_ACCESS_API_KEY,
short: "k",
},
database: {
type: "string",
default: process.env.DSQL_DB_NAME,
short: "d",
},
outfile: {
type: "string",
short: "o",
},
debug: {
type: "boolean",
default: false,
short: "d",
},
},
strict: false,
});
(async () => {
try {
const { apiKey: key, database, outfile, debug } = args.values;
if (debug) {
debugLog({
log: args.values,
label: "Arguments",
title: "Schema to Typedef",
addTime: true,
});
debugLog({
log: process.env.DSQL_FULL_ACCESS_API_KEY,
label: "process.env.DSQL_FULL_ACCESS_API_KEY",
title: "Schema to Typedef",
addTime: true,
});
debugLog({
log: process.env.DSQL_DB_NAME,
label: "process.env.DSQL_DB_NAME",
title: "Schema to Typedef",
addTime: true,
});
}
if (!database || typeof database !== "string")
throw new Error("Database name is required");
if (!key || typeof key !== "string")
throw new Error("API key is required");
if (!outfile || typeof outfile !== "string")
throw new Error("Outfile are required");
const schema = await datasquirel.getSchema({
key,
database,
user_id: 1,
});
const dbSchema = schema.payload as DSQL_DatabaseSchemaType | undefined;
if (!dbSchema) throw new Error("No schema found");
const definitions = dbSchemaToType({ dbSchema });
const finalOutfile = path.resolve(process.cwd(), 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);
}
})();