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

76 lines
2.1 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"),
});
// const mysql = require("mysql");
// const connection = mysql.createConnection({
// 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",
// });
const mysql = require("serverless-mysql");
const SSL_DIR = "/app/ssl";
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: {
ca: fs.readFileSync(`${SSL_DIR}/ca-cert.pem`),
},
},
});
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();
});