首页 > 解决方案 > Create yeoman generator with API's calls

问题描述

I’ve created a Yeoman generator which works OK, now I need to extend it with additional two questions.

This questions I already have

async prompting() {
  const prompts = [
    {
      name: "appName",
      message: "Project name: ",
      type: "input",
      default: this.props!.appName,
      validate(input: string) {
        const appName = validateAppName(input);
        return !appName[1] ? appName[0] : true;
      },
    },
    {
      type: "list",
      name: "tech",
      message: "Which tech?”,
      default: “cloud”,
      choices: [{ name: “cloud”}, { name: “onPrem” }}],
    },
    },
  ];

Now I need to add additional questions like on which namespace you want to create the project

{
  type: “list”,
  name: "namespace",
  suggestOnly: false,
  message: "which namespace: ",
  source: Namespace.searchNS,
  when: () => !isEmpty(this.namespace!.namespaceInstances),
  validate(val: boolean) {
    return val
      ? true
      : "choose a namespace where services are provisioned ";
  },
},

And the user should choose a namespace (the trick here that I need to run some logic i.e. rest call to get back the namespace list ) , and for this namespace I need to add another question . i.e for user choosen namespace I need to provide service list.

With service list, something like this.

{
    name: "serviceInstanceName",
    type: "rawlist",
    message:
      "Choose a service instance ",
    default: this.props!.namespace,
    choices: srvInstanceList,
    when: () =>
      srvInstanceList !== undefined && !isEmpty(srvInstanceList),
  },

What I need to do:

  1. Run an API (rest) call to get the namespace list, show it to the user as list
  1. When the user choose a specific namespace, I need to do an new rest call to get all the services in this namespace
  2. User choose service

where should I put the logic of each question and pass it to the next question

标签: javascriptnode.jstypescriptyeomanyeoman-generator

解决方案


我没有任何代码示例来支持答案,但如果我是你,我会:

  1. 运行 API (rest) 调用以获取命名空间列表,将其作为列表显示给用户
  2. 当用户选择一个特定的命名空间时,我需要做一个新的休息调用来获取这个命名空间中的所有服务
  3. 用户选择服务

对于与命名空间相关的问题,请使用choices将加载所有命名空间的属性和返回函数。同样,对于与服务相关的问题,使用choices属性和返回函数将加载命名空间中的所有服务。

这是关于choices

选择:(数组|函数)选择数组或返回选择数组的函数。如果定义为函数,则第一个参数将是当前询问者会话答案。数组值可以是简单的数字、字符串或包含名称(显示在列表中)、值(保存在答案哈希中)和简短(选择后显示)属性的对象。

在该函数中,您将获得第一个参数,其中包含用户对先前问题给出的答案。

此外,您可以使用when问题中的属性来确定是否应该根据先前的答案提出或跳过该问题。

参考:https ://github.com/SBoudrias/Inquirer.js/blob/master/README.md


推荐阅读