All files / src api.js

70.45% Statements 31/44
56.25% Branches 9/16
66.67% Functions 6/9
72.09% Lines 31/43
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 73 74 75 76 77 78 79 80 811x 1x 1x   1x 1x 1x 1x   1x   1x 3x 1x 1x 1x 1x 1x 1x   1x         2x 2x     2x     2x         2x 2x                                           2x 2x 2x             1x 3x 3x 3x 3x              
const path = require('path');
const maybe = require('call-me-maybe');
require('colors');
 
const { baseLinks } = require('./commands/link');
const utils = require('./utils/utils');
const console = require('./utils/console');
const invoke = require('./lib/invoke');
 
const linksPath = path.join(utils.sharedDirectoryPath(), 'links.json');
 
module.exports.run = (action, d, cb) => {
  if (this.key && this.key.startsWith('demo')) {
    return maybe(cb, new Promise((resolve) => {
      console.log('This is a demo API key!'.red);
      console.log('To get your own, run:');
      console.log('');
      console.log(`  ${'$'.grey} ${'api signup'.yellow}`);
      console.log('');
 
      return resolve();
    }));
  }
 
  // Can't reassign params
  let data = d;
  let callback = cb;
 
  // If no data is passed in, default to {}
  Iif (typeof data === 'function') {
    callback = data;
    data = {};
  } else Iif (!data) {
    data = {};
  }
 
  // Don't call api if there is a local link
  const localLinks = utils.fileExists(linksPath) ? require(linksPath) : baseLinks;
  Iif (localLinks.services[this.service] && localLinks.directories[process.cwd()].length) {
    const handler = require(path.join(process.cwd(), 'node_modules/api/utils/handler.js'));
    const errors = utils.buildErrors(localLinks.services[this.service]);
 
    const event = {
      name: action,
      data,
      pathOverride: localLinks.services[this.service],
      errors,
    };
 
    console.log(`Running ${this.service} from ${localLinks.services[this.service]}`.yellow);
 
    return maybe(callback, new Promise((resolve, reject) => {
      handler.go(event, undefined, (err, response) => {
        if (err) return reject(err);
 
        return resolve(response);
      });
    }));
  }
 
  return maybe(callback, new Promise((resolve, reject) => {
    return invoke(this.key, this.service, action, data).then((response) => {
      return resolve(response.body);
    }).catch((err) => {
      return reject(err.response.body);
    });
  }));
};
 
module.exports.config = (apiKey) => {
  this.key = apiKey;
  return (service) => {
    this.service = service;
    return this;
  };
};
 
/*
 * docsTest: This is an example for docs.test.js
 */