您可以在其中添加递归函数prompting()
钩。必须确保递归函数返回this.prompts
否则执行可能会停止。
我的策略如下所示
声明一个基于输入之一重复的递归函数
当你递归 in 时填充 propsthis.columns
将此实例变量传递给模板中writing()
hook
迭代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
}
);
}
TEMPLATE
{
"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
OUTPUT
{
"Type" : "AWS::Table",
"Properties" : {
"AttributeDefinitions" : [
{
"AttributeName": "ID",
"AttributeType": "Bigint"
}
{
"AttributeName": "Email",
"AttributeType": "String"
}
{
"AttributeName": "Password",
"AttributeType": "Text"
}
],
"TableName" : "User"
}
}