Я создаю генератор Yeoman для автоматизации создания нескольких таблиц базы данных. Мне нужно предоставить пользователям приглашение добавить несколько столбцов (комбинация столбцов ColumnName и DataType ниже).
У меня есть шаблон, сохраненный на моем диске, где я связываю динамические имена с входами пользователя и на основе этого шаблона, окончательный скрипт генерируется генератором Yeoman. Можете ли вы предложить, как заставить пользователя вводить повторяющиеся комбинации ColumnName/DataType, которые он хочет ввести?
var prompts = [{
type: 'input',
name: 'name',
message: 'The Table Name?'
}, {
type: 'input',
name: 'attributeName',
message: 'Define your Schema - ColumnName?',
default: 'ID'
},{
type: 'input',
name: 'attributeType',
message: 'Define your Schema - DataType?',
default: 'S'
}
];
return this.prompt(prompts).then(function (props) {
this.props = props;
}.bind(this));
Содержимое шаблона. Пользователь может вводить данные из столбцов 1/2/3/4 или более, и после того, как он делает это, приведенный ниже шаблон должен быть достаточно интеллектуальным, чтобы создать множество комбинаций колонок.
{
"Type" : "AWS::Table",
"Properties" : {
"AttributeDefinitions" :
{
"AttributeName" : "<%= attributeName %>",
"AttributeType" : "<%= attributeType %>"
},
{
"AttributeName" : "<%= attributeName %>",
"AttributeType" : "<%= attributeType %>"
},
"TableName" : <%= name %>,
}
}
Вы можете добавить рекурсивную функцию в ловушку prompting()
. Необходимо убедиться, что рекурсивная функция возвращает this.prompts
иначе выполнение может быть остановлено.
Моя стратегия работает как ниже
Объявите рекурсивную функцию, которая повторяется на основе одного из входных данных
this.columns
реквизит, как вы проходите через this.columns
Передайте эту переменную экземпляра в шаблон в writing()
this.columns
в шаблоне и заполните ваши столбцы
Первая запись в this.columns
будет содержать имя таблицы и детали первого столбца.
Проверьте приведенный ниже код, вы можете настроить его под свои нужды, если рекурсивная функция вызывается, как и ожидалось.
Есть дополнительная подсказка, которая спрашивает, повторять ли или нет. Это также может быть отброшено с некоторой логикой, но это зависит от вас.
побуждая()
prompting() {
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the remarkable ' + chalk.red('generator-react-starter-kit-relay-container') + ' generator!'
));
const tableNamePrompt = [{
type: 'input',
name: 'name',
message: 'The Table Name?'
}];
const columnPrompts = [{
type: 'input',
name: 'attributeName',
message: 'Define your Schema - ColumnName?',
default: 'ID'
}, {
type: 'input',
name: 'attributeType',
message: 'Define your Schema - DataType?',
default: 'S'
}, {
type: 'confirm',
name: 'repeat',
message: 'Do you want to add more columns?',
default: 'Y'
}]
this.columns = [];
const loop = (relevantPrompts) => {
return this.prompt(relevantPrompts).then(props => {
this.columns.push(props);
return props.repeat ? loop(columnPrompts) : this.prompt([]);
})
}
return loop([...tableNamePrompt, ...columnPrompts]);
}
А затем в хуке writing()
передайте переменную экземпляра columns
которую вы заполнили ранее.
пишу()
writing() {
this.fs.copyTpl(
this.templatePath('Schema.json'),
this.destinationPath('./Schema.json'),
{
columns: this.columns
}
);
}
ШАБЛОН
{
"Type" : "AWS::Table",
"Properties" : {
"AttributeDefinitions" : [
<% for (let i=0; i<columns.length; i++) { %>
{
"AttributeName": "<%= columns[i].attributeName %>",
"AttributeType": "<%= columns[i].attributeType %>"
}
<% } %>
],
"TableName" : "<%= (columns[0] || {}).name %>"
}
}
ОБРАЗЕЦ ВХОДА
_-----_ ╭──────────────────────────╮
| | │ Welcome to the │
|--(o)--| │ remarkable │
'---------´ │ generator-react-starter- │
( _´U'_ ) │ kit-relay-container │
/___A___\ /│ generator! │
| ~ | ╰──────────────────────────╯
__'.___.'__
´ ' |° ´ Y '
? The Table Name? User
? Define your Schema - ColumnName? ID
? Define your Schema - DataType? Bigint
? Do you want to add more columns? Yes
? Define your Schema - ColumnName? Email
? Define your Schema - DataType? String
? Do you want to add more columns? Yes
? Define your Schema - ColumnName? Password
? Define your Schema - DataType? Text
? Do you want to add more columns? No
ВЫХОД
{
"Type" : "AWS::Table",
"Properties" : {
"AttributeDefinitions" : [
{
"AttributeName": "ID",
"AttributeType": "Bigint"
}
{
"AttributeName": "Email",
"AttributeType": "String"
}
{
"AttributeName": "Password",
"AttributeType": "Text"
}
],
"TableName" : "User"
}
}