All files / dist/commands run.js

83.78% Statements 31/37
81.25% Branches 13/16
85.71% Functions 6/7
81.25% Lines 26/32
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 641x                     1x 1x 1x 1x   1x   1x 1x   1x 6x 5x   4x 4x   4x   4x 4x 4x 2x     4x 1x 1x     3x 1x     3x 3x     3x                            
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');
 
  let service = args[1];
  const action = args[2];
 
  const data = utils.parseArgs(args.splice(3));
 
  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 => {
      Iif (Buffer.isBuffer(response.file)) {
        process.stdout.write(response.file);
      } else {
        console.log(response);
      }
    }).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);
      }
    });
  });
};