Как добавить аутентификацию IBM API в мой код? - PullRequest
0 голосов
/ 25 апреля 2020

Watson Assistant поддерживает только один URL-адрес Webhook. Проблема в том, что у меня есть несколько узлов в Ассистенте, которые должны вызывать разные «Действия», которые я размещал в IBM Cloud Functions. Как я могу это сделать? Я пытался закодировать и «Действие», которое использует NPM Ax ios для вызова других «Действий», но не удается, так как не хватает аутентификации.

Может кто-нибудь сказать мне, как это сделать? Мне нужно, чтобы BASE URL был аутентифицирован через мой пользовательский API IBM Cloud для предоставления доступа к моему пространству имен.

Это созданное мною действие выступает в качестве «рассылки» для веб-хука для Watson Assistant.

/**
 *
 * main() will be run when you invoke this action
 *
 * @param Cloud Functions actions accept a single parameter, which must be a JSON object.
 *
 * @return The output of this action, which must be a JSON object.
 *
 * 
 * Version: 1.5 beta (API HUB)
 * Date: 24/04/2020
 * 
 */

const axios = require("axios");
// Change to your "BASE_URL". Type in the "Web Action" url without the name of it at the end. (must NOT contains the end '/')
// All "Actions" must be within the same namespace.
const BASE_URL = "https://jp-tok.functions.cloud.ibm.com/api/v1/web/
const POST = "post";
const GET = "get";
const ANY = "any";
const ALL = "all";

/* List all your API methods
    1. method - API Name (This is the "Actions" name at the end of the Web Action URL or just the name)
    2. attr - Attributes that should be available in the params object
    3. rule - Currently supports 2 rules;
                a) any - params is valid if "any" of the attributes are present
                b) all - params is valid only if all attributes are present
    4. httpmethod -Supports "POST" and "GET"
    5. contains - Use for validating GET URL parameters
*/
const API_METHODS = [{
        method: "Emails", // Change to your API method "Please put the function name located at the end of the url without "/" example "Email"
        attr: ["client_email", "department_email"],
        rule: ANY,
        httpmethod: POST,
        contains: null
    },
    {
        method: "testapi", // If Watson needs to "GET" information to a user or athenticate a user
        attr: [],
        rule: ALL,
        httpmethod: GET,
        contains: "?ID="
    },
]

// Returns true if the "params" is valid for the given API method
function isValidParam(method, params = {}) {
    var attributes = [];
    attributes = method.attr;
    var isAny = method.rule === ANY;
    for (let index = 0; index < attributes.length; index++) {
        const attr = attributes[index];
        if (isAny) {
            if (Object.hasOwnProperty.call(params, attr)) {
                return true;
            }
        } else {
            if (!Object.hasOwnProperty.call(params, attr)) {
                return false;
            }
        }
    }

    if (attributes.length === 0 && method.contains) {
        return (JSON.stringify(params).indexOf(method.contains) > -1)
    }

    // if the code reaches this position, inverse of "isAny" should return the actual validation status.
    return !isAny;
}

async function main(params) {
    var result = [];

    // Stop on first failure
    // We iterate through all API methods. Because there can be more than one matching API for the given param type
    for (let index = 0; index < API_METHODS.length; index++) {
        const apiMethod = API_METHODS[index];
        const url = BASE_URL + '/' + apiMethod.method;

        if (isValidParam(apiMethod, params)) {
            let response = apiMethod.httpmethod === POST ?
                await axios.post(url, params) :
                await axios.get(url + params); // Expects the parameter to be a string in this case like '?id=345343'

            console.log(response);

            result.push({
                sent: true,
                url: url,
                request: params,
            });
        }
    }

    return {
        sent: true,
        details: result
    };
}
// THe part of the code that needs to be copied to call other functions within the namespace.


/* const API_METHODS = [{
 method: "Emails", // Change to your API method "Please put the function name located at the end of the url without "/" example "Email"
 *   attr: ["bamboo_email", "latitude_email", "latest_r_email", "department_email"],
    rule: ANY,
    httpmethod: POST,
    contains: null
},
{
    method: "testapi", // If Watson needs to "GET" information to a user or athenticate a user
    attr: [],
    rule: ALL,
    httpmethod: GET,
    contains: "?ID="
},
]  */

Когда я запускаю его в Watson Assistant, я получаю следующую ошибку:

Тело ответа на вызов Webhook превысило [1050000] байт. Код ответа: 200, длительность запроса: 591, workspace_id: 150088ee-4e86 -48f5-afd5-5b4e99d171f8 ,action_id: a8fca023d456d1113e05aaf1f59b1b2b, url_called: https://watson-url-fetch.watson-url-fetcher: 443 / post? Url = https% 3A% 2F% 2Fjp-tok.functions.cloud1apiFF% 2wevFFF%% 2vbFF% %webFF%% 2bbFF% %webFF%% 2bbFF% 2F23d61581-fa68-4979-afa2-0216c17c1b29% 2FWatson + Assistant% 2FAssistant + Dispatch. json (и в журнале есть еще 1 ошибка)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...