All files / src/commands run.js

74.42% Statements 32/43
85.71% Branches 12/14
85.71% Functions 6/7
71.05% Lines 27/38
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 731x                     1x 1x 1x 1x   1x   1x 1x   1x 5x 4x   3x 3x 3x 3x 3x                         3x 3x 3x 2x     3x 1x 1x     2x 1x     2x 2x                            
module.exports.usage = `Run a service remotely
 
Usage: api run <service> <endpoint> [--team <team>]
 
--team is used to designate which team you would like to run this endpoint against.
This roughly equates to which API key we will use when invoking the service.
You may have access to some services from only certain teams, so this is important.
 
The team defaults to your personal user team.
`;
 
const request = require('../lib/request');
const utils = require('../utils/utils');
const console = require('../utils/console');
const invoke = require('../lib/invoke');
 
module.exports.aliases = ['invoke'];
 
module.exports.category = 'using';
module.exports.weight = 1;
 
module.exports.run = (args, opts) => {
  if (!args[1]) throw new Error('Missing service');
  if (!args[2]) throw new Error('Missing endpoint');
 
  const data = {};
  let service = args[1];
  const action = args[2];
  const passedData = utils.parseArgs(args.splice(3));
  for (const arg of passedData) {
    const i = arg.indexOf('=');
    const parsedArg = [arg.slice(0, i), arg.slice(i + 1)];
    let value = parsedArg[1];
    try {
      value = JSON.parse(parsedArg[1]);
    } catch (e) {
      // Already in proper format
      // console.log(e);
    }
    data[parsedArg[0]] = value;
  }
 
  return request.get('/users/me').then(response => JSON.parse(response)).then((user) => {
    let team = user.teams.find(t => t.personal);
    if (opts.team) {
      team = user.teams.find(t => t.name === opts.team);
    }
 
    if (!team) {
      console.log(`Cannot find team ${opts.team}`.red);
      return Promise.reject(new Error(`Cannot find team ${opts.team}`));
    }
 
    if (service.indexOf('/') > -1 && !service.startsWith('@')) {
      service = `@${service}`;
    }
 
    return invoke(team.key, service, action, data, true).then((response) => {
      console.log(response.body);
    }).catch((err) => {
      try {
        if (opts.json) {
          console.log(err.response.body);
        } else {
          console.error(err.response.body.error.red);
        }
      } catch (e) {
        console.error('Unexpected error occured'.red);
      }
    });
  });
};