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

63 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-11-05 11:12:42 +00:00
// @ts-check
2025-01-13 08:00:21 +00:00
import fs from "fs";
import path from "path";
2024-11-05 11:12:42 +00:00
require("dotenv").config({
path: path.resolve(__dirname, "../.env"),
});
2025-01-13 08:00:21 +00:00
import grabDbSSL from "../package-shared/utils/backend/grabDbSSL";
import mysql from "serverless-mysql";
2024-11-05 11:12:42 +00:00
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)
2025-01-13 08:00:21 +00:00
.then((result: any) => {
2024-11-05 11:12:42 +00:00
let typedefStart = `/**\n * @typedef {object} MYSQL_${table}_table_def\n`;
let typedefMid = "";
let typedefEnd = ` */`;
console.log("Result =>", result);
2025-01-13 08:00:21 +00:00
result.forEach((res: any) => {
2024-11-05 11:12:42 +00:00
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();
});