UNPKG

generator-loopback-kenx-migration

Version:
112 lines (90 loc) 3.11 kB
'use strict'; const Generator = require('yeoman-generator'); const chalk = require('chalk'); const yosay = require('yosay'); const toDbCase = (str) => { str = str.charAt(0).toLowerCase() + str.slice(1); return str.replace(/([A-Z])/g, function($1){return "_"+$1.toLowerCase()}); } const toModelNameCase = (str) => { str = str.charAt(0).toLowerCase() + str.slice(1); return str.replace(/([A-Z])/g, function($1){return "-"+$1.toLowerCase()}); } module.exports = class extends Generator { constructor(args, opts) { // Calling the super constructor is important so our generator is correctly set up super(args, opts) this.option('migration-path'); this.option('model-config-path'); this.migrationPath = this.option['migration-path']; this.modelConfigPath = this.option['model-config-path']; this.models = JSON.parse(this.fs.read(this.destinationPath('server/model-config.json')).toString()); let modelList = Object.keys(this.models); this.meta = this.models['_meta']; modelList.splice(0, 1); this.modelList = modelList; this.getModelSchema = (meta, name) => { if (!name) { return; } if (name !== 'ACL') { name = toModelNameCase(name); } for (let i=meta.sources.length-1; i>=0; i--) { if (this.fs.exists(this.destinationPath(`node_modules/${this.meta.sources[i]}/${name}.json`))) { return this.fs.readJSON(this.destinationPath(`node_modules/${this.meta.sources[i]}/${name}.json`)); break; } } } } prompting() { // Have Yeoman greet the user. this.log(yosay( 'Welcome to the superb ' + chalk.red('generator-loopback-kenx-migration') + ' generator!' )); const prompts = [ { type: 'list', name: 'modelName', message: 'Choose model', choices: this.modelList } ]; return this.prompt(prompts).then(props => { // To access props later use this.props.someAnswer; this.props = props; let model = this.getModelSchema(this.meta, this.props.modelName); let base = this.getModelSchema(this.meta, model.base); this.idInjection = model.idInjection; this.tableName = toDbCase(this.props.modelName); this.modelSchema = model.properties; if (!!base) { this.modelSchema = Object.assign(this.modelSchema, base.properties); } this.modelSchemaList = Object.keys(this.modelSchema); }); } writing() { console.log(this.props.modelName); this.fs.copyTpl( this.templatePath('migration.js'), this.destinationPath(`sql/migrations/${Date.now()}-create-${toModelNameCase(this.props.modelName)}.js`), { modelSchemaList: this.modelSchemaList, modelSchema: this.modelSchema, tableName: this.tableName, toDbCase, idInjection: this.idInjection, toLowerCase: (str) => { if (typeof str === 'object') { return str[0].toLowerCase(); } return str.toLowerCase(); } } ); } install() { } };