yargs#Arguments TypeScript Examples

The following examples show how to use yargs#Arguments. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: join.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const channel = new Channel(config)

  let joinChannelInput

  if (argv.interactive) {
    joinChannelInput = await prompts([
      {
        type: 'select',
        name: 'channelName',
        message: 'What is your channel name?',
        choices: channelList.map(x => ({
          title: x,
          value: x,
        })),
      },
      {
        type: 'select',
        name: 'orderer',
        message: 'Ordering service endpoint',
        choices: ordererList.map(x => ({
          title: x,
          value: x,
        })),
      },
    ], { onCancel })
  } else {
    const { name, orderer } = argv
    joinChannelInput = {
      channelName: name,
      orderer,
    }
  }

  await channel.join(joinChannelInput)
}
Example #2
Source File: down.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const orderer = new Orderer(config)

  const ordererHostNames: string[] = await (async () => {
    if (argv.interactive) {
      const bdkFile = new BdkFile(config)
      const fileNames = bdkFile.getDockerComposeList().orderer
      const fileNameSelect: Choice[] = fileNames.map((fileName) => {
        return {
          title: fileName,
          value: fileName,
        } as Choice
      })

      const ordererUpQuestion: prompts.PromptObject<string>[] = [{
        type: 'multiselect',
        name: 'ordererHostNames',
        message: 'What is your all orderers docker compose yaml',
        choices: fileNameSelect,
      }]
      const ordererOrg = await prompts(ordererUpQuestion, { onCancel })
      return ordererOrg.ordererHostNames
    } else if (argv.ordererHostNames) {
      return argv.ordererHostNames
    }
    return []
  })()

  if (ordererHostNames.length > 0) {
    await Promise.all(ordererHostNames.map(ordererHostname => orderer.down({ ordererHostname })))
  } else {
    logger.error('[x] Please add argument in command!')
  }
}
Example #3
Source File: add.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const peer = new Peer(config)

  if (!(config.orgName && config.orgDomainName)) {
    if (!config.orgName) logger.error('[x] There is not your org name! ( set in environment variable BDK_ORG_NAME')
    if (!config.orgDomainName) logger.error('[x] There is not your org name! ( set in environment variable BDK_ORG_DOMAIN')
  } else {
    let peerCount = 0

    if (argv.interactive) {
      const peerAddQuestions: prompts.PromptObject<string>[] = [{
        type: 'number',
        name: 'peerCount',
        message: `What is peer count in peer org ${config.orgName}`,
      }]
      const peerOrgConfig = await prompts(peerAddQuestions)
      peerCount = peerOrgConfig.peerCount
    } else {
      if (argv.peerCount) peerCount = argv.peerCount
    }

    if (peerCount > 0) {
      peer.add({ peerCount })
    } else {
      logger.error('[x] Please add argument in command!')
    }
  }
}
Example #4
Source File: add.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const orderer = new Orderer(config)

  if (!(config.orgName && config.orgDomainName)) {
    if (!config.orgName) logger.error('[x] There is not your org name! ( set in environment variable BDK_ORG_NAME')
    if (!config.orgDomainName) logger.error('[x] There is not your org name! ( set in environment variable BDK_ORG_DOMAIN')
  } else {
    let ordererHostnames: string[] = []

    if (argv.interactive) {
      const ordererQuestions: prompts.PromptObject<string>[] = [{
        type: 'list',
        name: 'hostnames',
        message: 'What is orderer org all hostname?',
      }]

      const ordererAddConfig = await prompts(ordererQuestions, { onCancel })
      ordererHostnames = ordererAddConfig.hostnames
    } else {
      if (argv.ordererHostnames) ordererHostnames = argv.ordererHostnames
    }

    if (ordererHostnames.length > 0) {
      orderer.add({ ordererHostnames, genesisFileName: 'genesis' })
    } else {
      logger.error('[x] Please add argument in command!')
    }
  }
}
Example #5
Source File: delete.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const network = new Network(config)

  let confirmDelete = true
  const networkName = argv.networkName ? argv.networkName : config.networkName

  if (!argv.force) {
    const response = await prompts({
      type: 'confirm',
      name: 'value',
      message: `Can you confirm delete blockchain network? [${networkName}]`,
      initial: false,
    }, { onCancel })

    confirmDelete = response.value
  }

  if (confirmDelete) {
    try {
      await network.delete(networkName)
    } catch (error: any) {
      logger.error(error.toString())
    }
  }
}
Example #6
Source File: down.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const peer = new Peer(config)

  const peerHostNames: string[] = await (async () => {
    if (argv.interactive) {
      const bdkFile = new BdkFile(config)
      const fileNames = bdkFile.getDockerComposeList().peer
      const fileNameSelect: Choice[] = fileNames.map((fileName) => {
        return {
          title: fileName,
          value: fileName,
        } as Choice
      })

      const peerUpQuestion: prompts.PromptObject<string>[] = [{
        type: 'multiselect',
        name: 'peerHostNames',
        message: 'What is your all peers docker compose yaml',
        choices: fileNameSelect,
      }]
      const peerOrg = await prompts(peerUpQuestion, { onCancel })
      return peerOrg.peerHostNames
    } else if (argv.peerHostNames) {
      return argv.peerHostNames
    }
    return []
  })()

  if (peerHostNames.length > 0) {
    await Promise.all(peerHostNames.map(peerHostname => peer.down({ peerHostname })))
  } else {
    logger.error('[x] Please add argument in command!')
  }
}
Example #7
Source File: up.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  logger.debug('exec explorer up')
  const explorer = new Explorer(config)
  let explorerUpInput

  if (argv.interactive) {
    explorerUpInput = await prompts([
      {
        type: 'text',
        name: 'user',
        message: 'What is your explorer default username?',
        initial: 'exploreradmin',
      },
      {
        type: 'text',
        name: 'pass',
        message: 'What is your explorer default password?',
        initial: 'exploreradminpw',
      },
      {
        type: 'number',
        name: 'port',
        message: 'What is your channel name?',
        initial: '8080',
      },
    ], { onCancel })
  } else {
    explorerUpInput = argv
  }

  await explorer.upForMyOrg(explorerUpInput)
}
Example #8
Source File: implementation.ts    From airnode with MIT License 6 votes vote down vote up
parseCliOverrides = (args: Arguments): ethers.Overrides => {
  const overrideMap = [
    { name: 'gas-limit', key: 'gasLimit', parseValue: (value: string) => ethers.BigNumber.from(value) },
    { name: 'gas-price', key: 'gasPrice', parseValue: (value: string) => ethers.utils.parseUnits(value, 'gwei') },
    { name: 'max-fee', key: 'maxFeePerGas', parseValue: (value: string) => ethers.utils.parseUnits(value, 'gwei') },
    {
      name: 'max-priority-fee',
      key: 'maxPriorityFeePerGas',
      parseValue: (value: string) => ethers.utils.parseUnits(value, 'gwei'),
    },
    { name: 'nonce', key: 'nonce', parseValue: parseInt },
  ];

  const overrides: ethers.Overrides = overrideMap.reduce((acc, override) => {
    if (args[override.name]) return { ...acc, [override.key]: override.parseValue(args[override.name] as string) };
    return acc;
  }, {});

  return overrides;
}
Example #9
Source File: up.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const peer = new Peer(config)

  const peerHostNames: string[] = await (async () => {
    if (argv.interactive) {
      const bdkFile = new BdkFile(config)
      const fileNames = bdkFile.getDockerComposeList().peer
      const fileNameSelect: Choice[] = fileNames.map((fileName) => {
        return {
          title: fileName,
          value: fileName,
        } as Choice
      })

      const peerUpQuestion: prompts.PromptObject<string>[] = [{
        type: 'multiselect',
        name: 'peerHostNames',
        message: 'What is your all peers docker compose yaml',
        choices: fileNameSelect,
      }]
      const peerOrg = await prompts(peerUpQuestion, { onCancel })
      return peerOrg.peerHostNames
    } else if (argv.peerHostNames) {
      return argv.peerHostNames
    }
    return []
  })()

  if (peerHostNames.length > 0) {
    for (const peerHostname of peerHostNames) {
      await peer.up({ peerHostname })
    }
  } else {
    logger.error('[x] Please add argument in command!')
  }
}
Example #10
Source File: init.ts    From nft-maker-js with Do What The F*ck You Want To Public License 6 votes vote down vote up
handler = (argv: Arguments<Options>): void => {
  getTasks(argv.force)
    .run()
    .catch(err => {
      console.error(err)
    })
    .finally(() => {
      process.exit(0)
    })
}
Example #11
Source File: create.ts    From typeorm-extension with MIT License 6 votes vote down vote up
async handler(raw: Arguments, exitProcess = true) {
        const args : DatabaseCreateArguments = raw as DatabaseCreateArguments;

        const dataSourceOptions = await buildDataSourceOptions({
            name: args.connection,
            configName: args.config,
            directory: args.root,
            dataSourceName: args.dataSource,
        });

        const context : DatabaseCreateContext = {
            ifNotExist: true,
            options: dataSourceOptions,
        };

        if (
            typeof args.initialDatabase === 'string' &&
            args.initialDatabase !== ''
        ) {
            context.initialDatabase = args.initialDatabase;
        }

        context.synchronize = args.synchronize === 'yes';

        await createDatabase(context);

        if (exitProcess) {
            process.exit(0);
        }
    }
Example #12
Source File: drop.ts    From typeorm-extension with MIT License 6 votes vote down vote up
async handler(raw: Arguments, exitProcess = true) {
        const args : DatabaseDropArguments = raw as DatabaseDropArguments;

        const dataSourceOptions = await buildDataSourceOptions({
            name: args.connection,
            configName: args.config,
            directory: args.root,
            dataSourceName: args.dataSource,
        });

        await dropDatabase({
            ifExist: true,
            options: dataSourceOptions,
        });

        if (exitProcess) {
            process.exit(0);
        }
    }
Example #13
Source File: seed.ts    From typeorm-extension with MIT License 6 votes vote down vote up
async handler(raw: Arguments, exitProcess = true) {
        const args : DatabaseSeedArguments = raw as DatabaseSeedArguments;

        const dataSourceOptions = await buildDataSourceOptions({
            name: args.connection,
            configName: args.config,
            directory: args.root,
            dataSourceName: args.dataSource,
        });

        setDataSourceOptions(dataSourceOptions);

        const dataSource = await useDataSource();

        await runSeeders(dataSource, {
            seedName: args.seed,
        });

        if (exitProcess) {
            process.exit(0);
        }
    }
Example #14
Source File: approve.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const channel = new Channel(config)

  const channelName: string = await (async () => {
    if (argv.interactive) {
      return (await prompts([
        {
          type: 'select',
          name: 'channelName',
          message: 'What is your channel name?',
          choices: channelEnvelopeList.map(x => ({
            title: x,
            value: x,
          })),
        },
      ], { onCancel })).channelName
    } else if (argv.channelName) {
      return argv.channelName
    } else {
      throw new ParamsError('Invalid params: Required parameter missing <channel-name>')
    }
  })()

  await channel.approve({ channelName })
}
Example #15
Source File: Runner.ts    From mpflow with MIT License 6 votes vote down vote up
/**
   * 注册 CLI 命令
   * @param command
   * @param describe
   * @param positional
   * @param options
   * @param handler
   */
  registerCommand<
    P extends Record<string, PositionalOptions> = Record<string, PositionalOptions>,
    O extends Record<string, Options> = Record<string, Options>
  >(
    command: CommandModule['command'],
    describe: CommandModule['describe'],
    positional: P,
    options: O,
    handler: (args: Arguments<InferredOptionTypes<P> & InferredOptionTypes<O>>) => void,
  ): void {
    this.service.registerCommand(command, describe, positional, options, handler)
  }
Example #16
Source File: package.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  logger.debug('exec chaincode package')

  const chaincode = new Chaincode(config)

  let packageChannelInput: ChaincodePackageType
  if (argv.interactive) {
    packageChannelInput = await prompts([
      {
        type: 'text',
        name: 'name',
        message: 'What is your chaincode name?',
        initial: 'fabcar',
      },
      {
        type: 'number',
        name: 'version',
        message: 'What is your chaincode version?',
        initial: 1,
      },
      {
        type: 'text',
        name: 'path',
        message: 'What is your chaincode path?',
        initial: './chaincode/fabcar/go',
      },
    ], { onCancel })
  } else {
    const { chaincodeName, chaincodeVersion, path } = argv
    packageChannelInput = { name: chaincodeName, version: chaincodeVersion, path }
  }
  await chaincode.package(packageChannelInput)
}
Example #17
Source File: Runner.ts    From mpflow with MIT License 6 votes vote down vote up
/**
   * 注册 CLI 命令
   * @param command
   * @param describe
   * @param positional
   * @param options
   * @param handler
   */
  registerCommand<
    P extends Record<string, PositionalOptions> = Record<string, PositionalOptions>,
    O extends Record<string, Options> = Record<string, Options>
  >(
    command: CommandModule['command'],
    describe: CommandModule['describe'],
    positional: P,
    options: O,
    handler: (args: Arguments<InferredOptionTypes<P> & InferredOptionTypes<O>>) => void,
  ): void {
    this._registerCommand(
      command,
      describe,
      yargs => {
        Object.keys(positional).forEach(key => (yargs = yargs.positional(key, positional[key])))
        yargs = yargs.options(options)
        return yargs
      },
      handler,
    )
  }
Example #18
Source File: up.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const orderer = new Orderer(config)

  const ordererHostNames: string[] = await (async () => {
    if (argv.interactive) {
      const bdkFile = new BdkFile(config)
      const fileNames = bdkFile.getDockerComposeList().orderer
      const fileNameSelect: Choice[] = fileNames.map((fileName) => {
        return {
          title: fileName,
          value: fileName,
        } as Choice
      })

      const ordererUpQuestion: prompts.PromptObject<string>[] = [{
        type: 'multiselect',
        name: 'ordererHostNames',
        message: 'What is your all orderers docker compose yaml',
        choices: fileNameSelect,
      }]
      const ordererOrg = await prompts(ordererUpQuestion, { onCancel })
      return ordererOrg.ordererHostNames
    } else if (argv.ordererHostNames) {
      return argv.ordererHostNames
    }
    return []
  })()

  if (ordererHostNames.length > 0) {
    for (const ordererHostname of ordererHostNames) {
      await orderer.up({ ordererHostname })
    }
  } else {
    logger.error('[x] Please add argument in command!')
  }
}
Example #19
Source File: export.ts    From bdk with Apache License 2.0 6 votes vote down vote up
handler = (argv: Arguments<OptType>) => {
  const org = new Org(config)

  const out: string = (() => {
    if (argv.out) {
      return argv.out
    } else {
      throw new ParamsError('Invalid params: Required parameter <out> missing')
    }
  })()

  org.exportConfig(out)
}
Example #20
Source File: add-system-channel.ts    From bdk with Apache License 2.0 5 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const peer = new Peer(config)

  const peerOrgName: string = await (async () => {
    if (argv.interactive) {
      return (await prompts([
        {
          type: 'text',
          name: 'name',
          message: 'What is peer org name?',
          initial: 'Test',
        },
      ], { onCancel })).name
    } else if (argv.peerOrgName) {
      return argv.peerOrgName
    } else {
      throw new ParamsError('Invalid params: Required parameter <peer-org-name> missing')
    }
  })()

  const orderer: string = await (async () => {
    if (argv.interactive) {
      return (await prompts([
        {
          type: 'select',
          name: 'orderer',
          message: 'Ordering service endpoint',
          choices: ordererList.map(x => ({
            title: x,
            value: x,
          })),
        },
      ], { onCancel })).orderer
    } else if (argv.orderer) {
      return argv.orderer
    } else {
      throw new ParamsError('Invalid params: Required parameter <orderer> missing')
    }
  })()

  await peer.addOrgToSystemChannel({ channelName: 'system-channel', orgName: peerOrgName, orderer })
}
Example #21
Source File: add.ts    From bdk with Apache License 2.0 5 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const peer = new Peer(config)

  const channelName: string = await (async () => {
    if (!channelList.length) throw new ParamsError('Invalid params: Please create blockchain network first')

    if (argv.interactive) {
      return (await prompts([
        {
          type: 'select',
          name: 'channelName',
          message: 'What is your channel name?',
          choices: channelList.map(x => ({
            title: x,
            value: x,
          })),
        },
      ], { onCancel })).channelName
    } else if (argv.channelName) {
      return argv.channelName
    } else {
      throw new ParamsError('Invalid params: Required parameter <channel-name> missing')
    }
  })()

  const peerOrgName: string = await (async () => {
    if (argv.interactive) {
      return (await prompts([
        {
          type: 'text',
          name: 'name',
          message: 'What is peer org name?',
          initial: 'Test',
        },
      ], { onCancel })).name
    } else if (argv.peerOrgName) {
      return argv.peerOrgName
    } else {
      throw new ParamsError('Invalid params: Required parameter <peer-org-name> missing')
    }
  })()

  await peer.addOrgToChannel({ channelName, orgName: peerOrgName })
}
Example #22
Source File: remove.ts    From bdk with Apache License 2.0 5 votes vote down vote up
handler = (argv: Arguments) => {
  logger.debug('exec orderer remove', argv.$0)
  // TODO
}
Example #23
Source File: ls.ts    From bdk with Apache License 2.0 5 votes vote down vote up
handler = (argv: Arguments) => {
  logger.debug('exec peer org ls', argv.$0)
  // TODO
}
Example #24
Source File: remove.ts    From bdk with Apache License 2.0 5 votes vote down vote up
handler = (argv: Arguments) => {
  logger.debug('exec peer remove', argv.$0)
  // TODO
}
Example #25
Source File: prepare-release.ts    From yaclt with Mozilla Public License 2.0 5 votes vote down vote up
PrepareReleaseCommand: CommandModule<
  Record<string, unknown>,
  PrepareReleaseCommandOptions
> = {
  command: "prepare-release",
  describe:
    "Gather the changelogs from `--logsDir` and compile them into `--changelogFile` using `--changelogTemplate`",
  builder: {
    changelogTemplate: {
      type: "string",
      describe:
        "The Handlebars template to use to generate the changelog additions. Can be a filepath to read the template from, or a template literal string.",
      demandOption: false,
      default: defaultChangelogTemplate,
    },
    releaseNumber: {
      type: "string",
      describe: "A label for the release",
      demandOption: true,
    },
    releaseBranchPattern: {
      type: "string",
      describe:
        "A pattern to generate a release branch name which will be automatically checked out before preparing the release.",
      demandOption: false,
    },
    edit: {
      describe:
        "After compiling the gathered changelogs, open the chagelog file in `$EDITOR`, if `$EDITOR` is defined",
      type: "boolean",
      default: false,
      demandOption: false,
    },
    ...ValidateCommandOptions,
    prePrepare: {
      describe:
        "A hook function to run before preparing the release changes. Throw an error or return false to halt execution. Only usable from a Javascript configuration file. May be async.",
      demandOption: false,
      hidden: true,
    },
    postPrepare: {
      describe:
        "A hook function to run after preparing the release changes. Only usable from a Javascript configuration file. May be async.",
      demandOption: false,
      hidden: true,
    },
    ...CliOptions,
  },
  handler: async (argv: Arguments<PrepareReleaseCommandOptions>) => {
    await runAction(async () => {
      const options: ActionPrepareReleaseOptions = {
        plumbing: argv.plumbing,
        changeTypes: argv.changeTypes,
        changelogFile: argv.changelogFile,
        logsDir: argv.logsDir,
        format: argv.format,
        validationPattern: argv.validationPattern,
        releaseBranchPattern: argv.releaseBranchPattern,
        edit: argv.edit ?? false,
        preValidate: argv.preValidate,
        postValidate: argv.postValidate,
        prePrepare: argv.prePrepare,
        postPrepare: argv.postPrepare,
        releaseNumber: argv.releaseNumber,
        template: argv.changelogTemplate,
      };

      await ActionPrepareRelease(options);
    });
  },
}
Example #26
Source File: validate.ts    From yaclt with Mozilla Public License 2.0 5 votes vote down vote up
ValidateCommand: CommandModule<
  Record<string, unknown>,
  ValidateCommandOptions
> = {
  command: "validate",
  describe: "Validate existing changelogs against the specified format",
  builder: options,
  handler: (argv: Arguments<ValidateCommandOptions>) => {
    if (
      argv.format === options["format"]?.default &&
      argv.validationPattern !== options["validationPattern"]?.default
    ) {
      Logger.warn(
        "Using default value for --format but not for --validationPattern. Most likely you want to use a custom value for --format."
      );
    }

    if (
      argv.validationPattern === options["validationPattern"]?.default &&
      argv.format !== options["format"]?.default
    ) {
      Logger.warn(
        "Using default value for --validationPattern but not --format. Most likely you want to use a custom value for --validationPattern."
      );
    }

    runAction(() => {
      const options: ActionValidateOptions = {
        plumbing: argv.plumbing,
        logsDir: argv.logsDir,
        format: argv.format,
        changeTypes: argv.changeTypes,
        validationPattern: argv.validationPattern,
        preValidate: argv.preValidate,
        postValidate: argv.postValidate,
      };

      ActionValidate(options);
    });
  },
}
Example #27
Source File: validator.ts    From yfm-docs with MIT License 5 votes vote down vote up
export function argvValidator(argv: Arguments<Object>): Boolean {
    try {
        // Combine passed argv and properties from configuration file.
        const pathToConfig = argv.config ? String(argv.config) : join(String(argv.input), YFM_CONFIG_FILENAME);
        const content = readFileSync(resolve(pathToConfig), 'utf8');
        Object.assign(argv, load(content) || {});
    } catch (error) {
        if (error.name === 'YAMLException') {
            log.error(`Error to parse ${YFM_CONFIG_FILENAME}: ${error.message}`);
        }
    }

    let lintConfig = {};
    try {
        const pathToConfig = join(String(argv.input), LINT_CONFIG_FILENAME);
        const content = readFileSync(resolve(pathToConfig), 'utf8');

        lintConfig = load(content) || {};
    } catch (error) {
        if (error.name === 'YAMLException') {
            log.error(`Error to parse ${LINT_CONFIG_FILENAME}: ${error.message}`);
        }
    } finally {
        const preparedLintConfig = merge(lintConfig, {
            'log-levels': {
                MD033: argv.allowHTML ? 'disabled' : 'error',
            },
        });

        Object.assign(argv, {lintConfig: preparedLintConfig});
    }

    try {
        const pathToRedirects = join(String(argv.input), REDIRECTS_FILENAME);
        const redirectsContent = readFileSync(resolve(pathToRedirects), 'utf8');
        const redirects = load(redirectsContent);

        validateRedirects(redirects as RedirectsConfig, pathToRedirects);
    } catch (error) {
        if (error.name === 'YAMLException') {
            log.error(`Error to parse ${REDIRECTS_FILENAME}: ${error.message}`);
        }

        if (error.code !== 'ENOENT') {
            throw error;
        }
    }

    if (argv.publish) {
        for (const [field, validator] of Object.entries(validators)) {
            const value = argv[field] ?? validator.defaultValue;

            if (!validator) {
                continue;
            }

            const validateFn = validator.validateFn ?? requiredValueValidator;

            if (!validateFn(value)) {
                throw new Error(validator.errorMessage);
            }

            argv[field] = value;
        }
    }

    return true;
}
Example #28
Source File: add.ts    From bdk with Apache License 2.0 5 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const ordererService = new Orderer(config)

  const orderer: string = await (async () => {
    if (argv.interactive) {
      return (await prompts([
        {
          type: 'select',
          name: 'orderer',
          message: 'Ordering service endpoint',
          choices: ordererList.map(x => ({
            title: x,
            value: x,
          })),
        },
      ], { onCancel })).orderer
    } else if (argv.orderer) {
      return argv.orderer
    } else {
      throw new ParamsError('Invalid params: Required parameter <orderer> missing')
    }
  })()

  const channelName: string = await (async () => {
    if (!channelList.length) throw new ParamsError('Invalid params: Please create blockchain network first')

    if (argv.interactive) {
      return (await prompts([
        {
          type: 'select',
          name: 'channelName',
          message: 'What is your channel name?',
          choices: channelList.map(x => ({
            title: x,
            value: x,
          })),
        },
      ], { onCancel })).channelName
    } else if (argv.channelName) {
      return argv.channelName
    } else {
      throw new ParamsError('Invalid params: Required parameter <channel-name> missing')
    }
  })()

  const orgName: string = await (async () => {
    if (argv.interactive) {
      return (await prompts([
        {
          type: 'text',
          name: 'name',
          message: 'What is orderer org name?',
          initial: 'Test',
        },
      ], { onCancel })).name
    } else if (argv.orgName) {
      return argv.orgName
    } else {
      throw new ParamsError('Invalid params: Required parameter <org-name> missing')
    }
  })()

  await ordererService.addOrgToChannel({ orderer, channelName, orgName })
}
Example #29
Source File: import.ts    From bdk with Apache License 2.0 5 votes vote down vote up
handler = async (argv: Arguments<OptType>) => {
  const org = new Org(config)

  const orgJsonList: OrgJsonType[] = await (async () => {
    if (argv.fileList) {
      const inputOrgJson: OrgJsonType[] = []

      argv.fileList.forEach(file => inputOrgJson.push(JSON.parse(fs.readFileSync(file).toString())))

      return inputOrgJson
    } else if (argv.interactive) {
      const orgCount: number = await (async () => {
        return (await prompts([
          {
            type: 'number',
            name: 'orgCount',
            message: 'How many org do you want to add?',
            min: 1,
            initial: 1,
          },
        ], { onCancel })).orgCount
      })()

      const orgJsons: OrgJsonType[] = []
      for (let i = 0; i < orgCount; i++) {
        const orgJson = await prompts([
          {
            type: 'text',
            name: 'orgName',
            message: `What is peer org ${i} name?`,
            initial: 'Test',
          },
          {
            type: 'select',
            name: 'orgType',
            message: `What is peer org ${i} type?`,
            choices: [
              { title: 'Orderer', value: 'Orderer' },
              { title: 'Peer', value: 'Peer' },
            ],
            initial: 1,
          },
          {
            type: 'text',
            name: 'jsonFile',
            message: `What is peer org ${i} json file path?`,
          },
        ], { onCancel })

        orgJsons.push({
          name: orgJson.orgName,
          json: JSON.parse(fs.readFileSync(orgJson.jsonFile).toString()),
        })
      }

      return orgJsons
    }

    throw new ParamsError('Invalid params: Required parameter missing')
  })()

  org.importConfig(orgJsonList)
}