|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const Cli = require('lib/cli'); |
| 4 | +const inquirer = require('inquirer'); |
| 5 | +const yaml = require('js-yaml'); |
| 6 | + |
| 7 | + |
| 8 | +module.exports = resource => { |
| 9 | + const options = { |
| 10 | + [resource.name]: { |
| 11 | + description: `${resource.title} ID`, |
| 12 | + type: 'string', |
| 13 | + required: true, |
| 14 | + }, |
| 15 | + }; |
| 16 | + |
| 17 | + return Cli.createCommand('edit', { |
| 18 | + description: `Edit ${resource.title}`, |
| 19 | + resource: resource, |
| 20 | + dirname: __dirname, |
| 21 | + options: Object.assign({}, options, resource.options), |
| 22 | + handler: async args => { |
| 23 | + const url = `${resource.url(args)}/${args[resource.name]}`; |
| 24 | + const result = await args.helpers.api.get(url); |
| 25 | + |
| 26 | + const questions = { |
| 27 | + type: 'editor', |
| 28 | + name: 'input', |
| 29 | + message: 'Specify the name and access policy of the token.', |
| 30 | + default: yaml.safeDump({ |
| 31 | + name: result.name, |
| 32 | + access: result.access.map(access => ({ |
| 33 | + method: access.method, |
| 34 | + path: access.path, |
| 35 | + })), |
| 36 | + }), |
| 37 | + validate: function (text) { |
| 38 | + try { |
| 39 | + yaml.safeLoad(text); |
| 40 | + } catch (e) { |
| 41 | + return `You can not change the data format (YAML). The data entered is not a valid YAML document.\n${e.message}`; |
| 42 | + } |
| 43 | + return true; |
| 44 | + }, |
| 45 | + }; |
| 46 | + |
| 47 | + const {input} = await inquirer.prompt(questions); |
| 48 | + const data = yaml.safeLoad(input); |
| 49 | + const requests = []; |
| 50 | + if ('name' in data && data.name !== result.name) { |
| 51 | + requests.push(args.helpers.api.patch(`${args.$node.parent.config.url(args)}/${args[resource.name]}`, { |
| 52 | + name: data.name, |
| 53 | + })); |
| 54 | + } |
| 55 | + if ('access' in data) { |
| 56 | + // Add new access |
| 57 | + requests.push(...data.access |
| 58 | + .filter(access => !result.access.find(acc => acc.path === access.path && acc.method === access.method)) |
| 59 | + .map(access => args.helpers.api.post(`${url}/access`, access))); |
| 60 | + // Remove missing access |
| 61 | + requests.push(...result.access |
| 62 | + .filter(access => !data.access.find(acc => acc.path === access.path && acc.method === access.method)) |
| 63 | + .map(access => args.helpers.api.delete(`${url}/access/${access._id}`))); |
| 64 | + } |
| 65 | + for (const req in requests) { |
| 66 | + await req; // Perform asynchronously for now. |
| 67 | + } |
| 68 | + return args.helpers.api.get(url) |
| 69 | + .then(result => args.helpers.sendOutput(args, result)); |
| 70 | + }, |
| 71 | + }); |
| 72 | +}; |
0 commit comments