rpc | store rpc result | get environment | Search

The getResult function acts as a command dispatcher, verifying user permissions and extracting parameters before executing a requested command.

Run example

npm run import -- "rpc result"

rpc result

var path = require('path');
var assert = require('assert');
var importer = require('../Core');
var groupPermissions = importer.import("test get permissions");
var getParameters = importer.import("function parameters");

function getResult(props) {
    if (props.result === null) {
        throw new Error('command not found, please specify a command');
    }
    assert(props.result.id, 'something is terribly wrong with this execution: '
           + JSON.stringify(props.result));
    
    // filter permissions compare id with permissions
    props.allowed = Object.keys(groupPermissions(props.circles || ['Public'])).includes(props.result.id);
    if(!props.allowed) {
        throw new Error('Would have run "' + props.result.id
                        + '" but you don\'t have permission. '
                        + 'Deploy your own server to get access to all RPC functions.');
    }
    
    console.log(`running ${props.result.id} (${props.command})`)    
    // TODO: make this nicer, ugly because importer doesn't conform to the same importing
    //   style and therefore functions are missing from the context when loaded separately.
    // This is maybe a sign there is something wrong with this style of dependency injection
    var commandResult = importer.import("result.id");
    if(commandResult && typeof commandResult[Object.keys(commandResult)[0]] === 'function') {
        commandResult = commandResult[Object.keys(commandResult)[0]];
    }
       
    if(typeof commandResult === 'function') {
        var parameterValues = [];
        if(props.body) {
            if(typeof props.body[0] !== 'undefined') {
                parameterValues = props.body;
            } else {
                parameterValues = getParameters(commandResult).slice(1).map((k, i) => {
                    const p = props.body[k] || props.body[i];
                    if(typeof p === 'undefined' || p === 'undefined') {
                        return;
                    }
                    return p;
                });
            }
        }
        console.log(`calling ${props.result.id} (${props.command}) ${JSON.stringify(parameterValues)}`)    
        return commandResult.apply(null, parameterValues);
    }
    return commandResult;
}

module.exports = getResult;

What the code could have been:

const path = require('path');
const assert = require('assert');
const importer = require('../Core');

// Define a function to check permissions
const hasPermission = (id, circles, groupPermissions) => {
    const permissions = groupPermissions(circles || ['Public']);
    return Object.keys(permissions).includes(id);
};

// Define a function to get parameter values
const getParameterValues = (props, commandResult, body) => {
    const parameters = getParameters(commandResult).slice(1);
    const values = parameters.map((k, i) => {
        const p = body[k] || body[i];
        if (typeof p === 'undefined' || p === 'undefined') {
            return;
        }
        return p;
    });
    return values;
};

// Define the getResult function
const getResult = (props) => {
    // Check if result is provided
    if (props.result === null) {
        throw new Error('Command not found, please specify a command');
    }

    // Check if result id is valid
    assert(props.result.id, `Invalid result ID: ${JSON.stringify(props.result)}`);

    // Check permissions
    const permitted = hasPermission(props.result.id, props.circles || ['Public'], groupPermissions);
    if (!permitted) {
        throw new Error(`Insufficient permissions to run "${props.result.id}".`);
    }

    // Log command execution
    console.log(`Running ${props.result.id} (${props.command})`);

    // Import command function
    try {
        const commandFunction = importer.import(props.result.id);
        const functionName = Object.keys(commandFunction)[0];

        // Check if command function is valid
        if (typeof commandFunction[functionName]!== 'function') {
            throw new Error(`Invalid command function: ${props.result.id}`);
        }

        // Get parameter values
        const body = props.body || {};
        const values = getParameterValues(props, commandFunction, body);

        // Log command execution with parameters
        console.log(`Calling ${props.result.id} (${props.command}) with parameters: ${JSON.stringify(values)}`);

        // Execute command function with parameters
        return commandFunction[functionName].apply(null, values);
    } catch (error) {
        // If importing command function fails, return an error
        return error;
    }
};

module.exports = getResult;

This code snippet defines a function getResult that handles the execution of a command based on provided parameters and permissions.

Here's a breakdown:

  1. Initialization:

  2. getResult Function:

  3. Command Execution:

In essence, this code acts as a command dispatcher, ensuring proper authorization and parameter handling before executing a user-requested command.