Map command argument options to an object
Today I was looking for a way to convert some code from the "node-program" cli definitions to something that works with Kado 4 CommandServers.
The issue I kept running into converting these methods were that the CLI options were typically sent in a long and short form so they have to be processed in order to return the proper data.
I came up with this method and usage which I employed and I think will work well.
Consider a command like
node app client create -n Foo -e foo@foo.com -p 555-555-5555
First some method usage
async create (opts) {
const argList = [['name', 'n'], ['email', 'e'], ['phone', 'p']]
const args = GetOpt.mapArguments(argList, opts)
const clientData = {
name: args.name,
email: args.email,
phoneNumber: args.phone
}
}
Second the method to collate the options:
class GetOpt {
static mapArguments (argList, opts) {
const args = {}
argList.map((argName) => {
const full = argName.shift()
const short = argName.shift()
if (short) args[full] = opts[short] || opts[full]
else args[full] = opts[full]
})
return args
}
}