datasquirel/engine/schema-to-typedef.ts
Benjamin Toby 6e32bbb4e0 Updates
2025-04-17 10:49:34 +01:00

72 lines
2.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";
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",
default: process.env.DSQL_DB_NAME,
short: "o",
},
},
strict: false,
});
(async () => {
try {
const { apiKey: key, database, outfile } = args.values;
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) {
console.log("Error:", error.message);
process.exit(1);
}
})();