dsql-admin/dsql-app/utils/sqlToType.js
2024-11-06 13:57:20 +01:00

63 lines
1.8 KiB
JavaScript

// @ts-check
const fs = require("fs");
const path = require("path");
require("dotenv").config({
path: path.resolve(__dirname, "../.env"),
});
const grabDbSSL = require("../package-shared/utils/backend/grabDbSSL");
const mysql = require("serverless-mysql");
const connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: process.env.DSQL_DB_NAME,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
const tableIndex = process.argv.findIndex((str) => str.match(/--table|-t/));
const table = tableIndex >= 0 ? process.argv[tableIndex + 1] : null;
if (!table) {
console.log(
"Please add a table flag to the arguments: Eg. '--talbe <table_name>'"
);
process.exit();
}
connection
.query("SHOW COLUMNS FROM" + " " + table)
.then((result) => {
let typedefStart = `/**\n * @typedef {object} MYSQL_${table}_table_def\n`;
let typedefMid = "";
let typedefEnd = ` */`;
console.log("Result =>", result);
result.forEach((/** @type {any} */ res) => {
const parsedResult = JSON.parse(JSON.stringify(res));
const { Field, Type, Null, Key, Default, Extra } = parsedResult;
const type = (() => {
if (Type?.match(/int/i)) return "number";
return "string";
})();
typedefMid += ` * @property {${type}} [${Field}] - NULL=\`${Null}\` Key=\`${Key}\` Default=\`${Default}\` Extra=\`${Extra}\`\n`;
});
console.log(typedefStart + typedefMid + typedefEnd);
process.exit();
})
.catch((error) => {
console.log(error.message);
})
.finally(() => {
/** ********************* Clean up */
connection.end();
});