fibery-unofficial
Version:
The unofficial Fibery Node.js library
65 lines (54 loc) • 2.33 kB
JavaScript
const request = require('request-promise-native');
const Type = require('./type');
const Field = require('./field');
const Entity = require('./entity');
const Command = class {
constructor(host, token) {
this._host = host;
this._token = token;
this._commandsEndpoint = '/api/commands';
this.createTypeBatchCmd = Type.commands.createTypeBatchCmd;
this.renameTypeBatchCmd = Type.commands.renameTypeBatchCmd;
this.deleteTypeBatchCmd = Type.commands.deleteTypeBatchCmd;
this.createFieldBatchCmd = Field.commands.createFieldBatchCmd;
this.renameFieldBatchCmd = Field.commands.renameFieldBatchCmd;
this.deleteFieldBatchCmd = Field.commands.deleteFieldBatchCmd;
this.queryEntityCmd = Entity.commands.queryEntityCmd;
this.createEntityBatchCmds = Entity.commands.createEntityBatchCmds;
this.updateEntityBatchCmds = Entity.commands.updateEntityBatchCmds;
this.addToEntityCollectionFieldBatchCmds = Entity.commands.addToEntityCollectionFieldBatchCmds;
this.removeFromEntityCollectionFieldBatchCmds = Entity.commands.removeFromEntityCollectionFieldBatchCmds;
this.deleteEntityBatchCmds = Entity.commands.deleteEntityBatchCmds;
}
executeBatch(commands) {
return request.post({
url: 'https://' + this._host + this._commandsEndpoint,
headers: {
'Authorization': `Token ${this._token}`,
'X-Client': 'Unofficial JS'
},
json: commands
}).then(response => {
const errors = response.reduce((acc, res, i) => {
if (!res.success) {
return acc.concat(`Error while executing command '${commands[i].command}': ${res.result.message}`)
} else {
return acc;
}
}, []);
if (errors.length) {
throw new Error(errors.join('\n'));
}
return response.map(res => res.result);
}).catch(err => {
throw new Error(err)
});
}
execute(command) {
return this.executeBatch([{
'command': command.command,
'args': command.args
}]).then(results => results[0]);
}
};
module.exports = Command;