dsql-admin/dsql-app/utils/sqlToType.js

63 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-11-05 11:12:42 +00:00
// @ts-check
const fs = require("fs");
const path = require("path");
require("dotenv").config({
path: path.resolve(__dirname, "../.env"),
});
2024-11-06 12:57:20 +00:00
const grabDbSSL = require("../package-shared/utils/backend/grabDbSSL");
2024-11-05 11:12:42 +00:00
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",
2024-11-06 12:57:20 +00:00
ssl: grabDbSSL(),
2024-11-05 11:12:42 +00:00
},
});
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();
});