All files / src/commands unlink.js

95.65% Statements 22/23
66.67% Branches 4/6
100% Functions 4/4
100% Lines 20/20
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 391x             1x   1x 1x 1x   1x   1x 2x 2x   2x     2x 1x 1x 1x   1x   1x 1x   1x   2x 2x      
module.exports.usage = `Remove linked services
 
Usage:
  api unlink # Removes all local links from service in current directory
  api unlink math # Removes local link to math service in current directory
`;
 
module.exports.category = 'utility';
 
const utils = require('../utils/utils');
const path = require('path');
const fs = require('fs');
 
const packageJson = require('../lib/package-json');
 
module.exports.run = (args) => {
  const linksPath = path.join(utils.sharedDirectoryPath(), 'links.json');
  const links = utils.fileExists(linksPath) ? require(linksPath) : {};
 
  const pjsonName = packageJson().get('name');
 
  // Don't want service to be linked anymore
  if (args.length === 1) {
    delete links.services[pjsonName];
    for (const p in links.directories) {
      links.directories[p] = links.directories[p].filter(s => s !== pjsonName);
    }
    console.log(`Removed ${pjsonName.green} from links`);
  } else { // unlink service from consumer
    for (const p in links.directories) {
      links.directories[p] = links.directories[p].filter(s => s !== args[1]);
    }
    console.log(`Removed ${args[1]} from links`);
  }
  fs.writeFile(linksPath, JSON.stringify(links), (err) => {
    Iif (err) console.error(err);
  });
};