MySQLtx Struct Generator
Generate mysqltx structs from your database schema.
The component can be installed as simple as:
npm install --save mysqltx-struct-generator
Usage
This component is built to fetch your current database schema and translate it into TypeScript code. You may save the code into files or find any other use for it on your own discretion.
import { ConnectionManager } from 'mysqltx';
import { Schema, Generator } from 'mysqltx-struct-generator';
const cm = new ConnectionManager({
// ... connection options here ...
});
try {
// load schema for the database named when creating connection manager
const schema = await cm.connection(
async (connection) => {
return await Schema.load(connection);
}
);
// initialize a generator with the options you see fit
const generator = new Generator({
camelCase: true,
namespace: true,
namespacePostfix: 'Table',
enumPostfix: 'Enum'
});
// you can either generate code for all tables at once
console.log(
generator.generateCode(schema.tables)
);
// or for each table separately
for (const table of schema.tables) {
console.log(
generator.generateCode([ table ])
);
}
} finally {
await cm.close();
}
Generating structs for your schema would definitely be helpful for an easy query result parsing development experience.
Advanced
In some projects you may need for a more precise control over identifier names or header generation. For this case you may use something called transformers.
// initialize a generator with the options you see fit
const generator = new Generator(
{
// these are regular options
namespace: true,
camelCase: true
},
{
// these are transformers
header: (importLine: string, generator: Generator) =>
[
'',
'// GENERATED, DO NOT EDIT DIRECTLY'
importLine,
'',
''
].join(g.settings.eol),
namespaceName: (tableName: string, generator: Generator) =>
'MyPrefixedNamespaceNamed' +
`${generator.getFormattedIdentifier(tableName, true)}${generator.settings.namespacePostfix}`,
// ... etc
}
});
You may override all, some or none of the transformers up to your own discretion. The best way to know if it would work for you is to give it a try!
Important notes:
- This component is still in it's early days so you may expect substantional and backward-incompatible changes down the road.
Enjoy!