Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add initial implementation #2

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 33 additions & 0 deletions lib/mermaid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict';

const serializeProp = (prop) => ` ${prop.type} ${prop.name}`;

const serializeEntities = (entityInfos) =>
entityInfos
.map(
({ name, props }) =>
`${name} {\n` + props.map(serializeProp).join('\n') + '\n}\n'
)
.join('\n');

const serializeRelation = (relation) => {
const sourceConnector = relation.unique ? '|o' : '}o';
const targetConnector =
(relation.required ? '|' : 'o') + (relation.many ? '{' : '|');
return (
`${relation.source} ${sourceConnector}-` +
`-${targetConnector} ${relation.target} : ${relation.name}`
);
};

const serializeRelations = (entityInfos) =>
entityInfos
.filter(({ relations }) => relations.length !== 0)
.map(({ relations }) => relations.map(serializeRelation).join('\n'))
.join('\n\n');

const serializeERD = (entityInfos) => `erDiagram
${serializeEntities(entityInfos)}
${serializeRelations(entityInfos)}`;

module.exports = serializeERD;
49 changes: 49 additions & 0 deletions lib/plantUML.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict';

const serializeProp = (prop) =>
` ${prop.required ? '*' : ''}${prop.name}: ${prop.type}`;

const serializeEntities = (entityInfos) =>
entityInfos
.map(
({ name, props }) =>
`entity ${name} {\n` + props.map(serializeProp).join('\n') + '\n}\n'
)
.join('\n');

const serializeRelation = (relation, config) => {
const sourceConnector = relation.unique ? '|o' : '}o';
const targetConnector =
(relation.required ? '|' : 'o') + (relation.many ? '{' : '|');
const property =
`${relation.source} ${sourceConnector}-` +
`-${targetConnector} ${relation.target}`;
return config.annotatedRelations
? property + ` : ${relation.name}`
: property;
};

const serializeRelations = (entityInfos, config) =>
entityInfos
.filter(({ relations }) => relations.length !== 0)
.map(({ relations }) =>
relations
.map((relation) => serializeRelation(relation, config))
.join('\n')
)
.join('\n\n');

const serializeERD = (entityInfos, config) => `@startuml

' hide the spot
hide circle

' avoid problems with angled crows feet
skinparam linetype ortho

${serializeEntities(entityInfos)}
${serializeRelations(entityInfos, config)}

@enduml`;

module.exports = serializeERD;
118 changes: 117 additions & 1 deletion metagram.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,119 @@
#!/usr/bin/env node

'use strict';

/* This is a stub */
const fs = require('fs');

const metaschema = require('metaschema');
const { toUpperCamel } = require('metautil');

const yargs = require('yargs');

const plantUML = require('./lib/plantUML.js');
const mermaid = require('./lib/mermaid.js');

const SERIALIZERS = { plantUML, mermaid };

const args = yargs
.option('path', {
alias: 'p',
type: 'string',
demandOption: true,
describe: 'Path to the directory that contains schemas',
})
.option('type', {
alias: 't',
type: 'string',
default: 'plantUML',
choices: ['plantUML', 'mermaid'],
})
.option('output', {
alias: 'o',
type: 'string',
describe:
'Path to the output file. ' +
'If not provided, output will be printed to stdout',
})
.option('warn', {
alias: 'w',
type: 'boolean',
default: true,
describe: 'Print metaschema warnings',
})
.option('annotatedRelations', {
type: 'boolean',
default: true,
describe:
'Annotate relation with a name of a property ' +
'that represents the relation. Only applies to PlantUML',
})
.help().argv;

run(args).catch((error) => console.error(error));

async function run({ path, type, output, warn, annotatedRelations }) {
const model = await metaschema.Model.load(path);
if (warn && model.warnings.length !== 0)
model.warnings.forEach((warning) => console.warn(warning));
const entityInfos = [...model.entities].map(([name, schema]) => ({
name,
...getPropsAndRelations(model, schema),
}));

const erd = SERIALIZERS[type](entityInfos, { annotatedRelations });
print(output, erd);
}

function getPropsAndRelations(model, schema, path = '') {
/* { name, type, required } */
const props = [];
/* { name: source, target, unique, required, many } */
const relations = [];

for (const [field, definition] of Object.entries(schema.fields)) {
const name = path ? path + toUpperCamel(field) : field;
if (definition instanceof metaschema.Schema) {
const fieldInfo = getPropsAndRelations(model, definition, name);
props.push(...fieldInfo.props);
relations.push(...fieldInfo.relations);
} else if (model.entities.has(definition.type)) {
props.push({
name,
type: 'Id',
required: definition.required,
});
/* It's possible that we should check whether target is a detail*/
relations.push({
name,
source: schema.name,
target: definition.type,
unique: definition.unique,
required: definition.required,
many: definition.many,
});
} else {
props.push({
name,
type: definition.type,
required: definition.required,
});
}
}

for (const [name, index] of Object.entries(schema.indexes)) {
if (!index.many) continue;
relations.push({
name,
source: schema.name,
target: index.many,
many: true,
});
}

return { props, relations };
}

function print(path, erd) {
if (!path) return void console.log(erd);
return fs.writeFileSync(path, erd);
}