플레이어 관리 샘플 설정

이 페이지에서는 새 플레이어의 기본 샘플이 어떻게 작성되는지 설명합니다. 여기에는 기본 인증과 플레이어 관리 API 샘플에서 AJAX가 사용되는 방법에 대한 세부 정보가 포함됩니다.

서문

단계별로 다음을 수행합니다. Curl 문을 사용하여 API와 상호 작용하는 플레이어 관리 문서입니다. API 호출이 이루어졌을 때 대화식으로 암호를 입력하라는 메시지가 표시됩니다. 컬 (curl) 에서는 잘 작동하지만 이러한 종류의 대화식 인증은 응용 프로그램을 빌드 할 때 불가능합니다.

여기에서는 플레이어 관리 작업을위한 웹 클라이언트를 구축하기 위해 JavaScript 및 XMLHttpRequest (AJAX라고도 함)를 사용하여 API 요청을 만드는 방법을 배웁니다.

플레이어 관리 API는 CORS가지원되며 Brightcove 로그인 자격 증명을 사용한 기본 인증을 허용하므로 플레이어 관리 API 샘플에서와 같이 웹 페이지에서 직접 API 요청을 할 수 있습니다. 브라이트코브의 다른 RESTful API에는 OAuth를 통한 인증이 필요합니다 . 액세스 토큰을 검색하는 데 사용되는 API는 CORS를 지원하지 않으므로 (API 자체도 아님) 서버 측 앱을 통해 요청해야합니다. 보다 REST API 사용 REST API에 액세스하기 위해 웹 UI 및 프록시를 사용하여 하이브리드 앱을 빌드하는 방법에 대한 가이드입니다. 이는 더 안전하고 HTTP 연결을 통해 자격 증명을 전송하지 않기 때문에 프로덕션에서 플레이어 관리 API를 사용하는 앱에 대해 권장하는 접근 방식입니다.

기본 인증

단계별로 다음을 수행합니다. Curl 문을 사용하여 API와 상호 작용하는 플레이어 관리 문서입니다. API 호출이 이루어졌을 때 대화식으로 암호를 입력하라는 메시지가 표시됩니다. 컬 (curl) 에서는 잘 작동하지만 이러한 종류의 대화식 인증은 응용 프로그램을 빌드 할 때 불가능합니다.

앱을 빌드 할 때 기본 인증을 사용할 수 있습니다. 헤더에서 base-64로 인코딩 된 ASCII 문자열로 암호화 된 자격 증명을 보내야합니다. JavaScript btoa()메서드를 사용하여 인코딩을 수행할 수 있습니다. 예를 들어 양식에서account_usernameaccount_password가 채워진다고 가정하면 Authorization 헤더는 다음과 같이 표시됩니다.

     "Authorization": "Basic " + btoa(account_username + ":" + account_password),

AJAX

이러한 샘플은 curl 명령문을 사용하는 대신 JavaScript를 사용하여 API와 통신합니다. 이는 AJAX를 사용하여 API에 요청을 발행하는 것을 의미합니다. 특정 예제 요청은 다음과 같습니다.

    $.ajax({
        type: "DELETE",
        headers: {
        "Authorization": "Basic " + btoa("username:password"),
        "Content-Type": "application/json"
        },
        url: "https://players.api.brightcove.com/v2/accounts/123456789/players/478772a5-a2f2-44c6-a26b-2d7234bd97f5",
        success: ajaxSuccess,
        error: ajaxError
    });

관련success핸들러와error핸들러는 다음과 같을 수 있습니다.

    var ajaxSuccess = function (data) {
        document.getElementById("jsonResponse").innerHTML = JSON.stringify(data,null,2);
        };
    
        var ajaxError = function (data) {
        console.log("error data: ");
        console.log(data);
    };

물론 위와 같이 AJAX 호출의 모든 정보를 하드 코딩하고 싶지는 않으므로 다음과 같이 재사용 가능한 함수에 대한 실제 호출을 추상화하는 것이 좋습니다.

    var makeAjaxCall = function (callURL, callType, callData) {
        if (callData) {
            $.ajax({
                type: callType,
                headers: {
                    "Authorization": "Basic " + btoa(account_username + ":" + account_password),
                    "Content-Type": "application/json"
                },
                url: callURL,
                data: JSON.stringify(callData),
                success: ajaxSuccess,
                error: ajaxError
            });
        } else {
            $.ajax({
            type: callType,
            headers: {
                "Authorization": "Basic " + btoa(account_username + ":" + account_password),
                "Content-Type": "application/json"
            },
            url: callURL,
            success: ajaxSuccess,
            error: ajaxError
            });
        }
    };

이제 함수를 호출 할 준비가되었습니다. 다음 예제에서는account_id , account_passwordaccount_username값이 모두 양식에서 추출됩니다.

    var getPlayerInfo = function () {
        account_id = document.getElementById("account_id").value,
        account_password = document.getElementById("account_password").value,
        account_username = document.getElementById("account_username").value;
        call_url = "https://players.api.brightcove.com/v2/accounts/" + account_id + "/players";
        makeAjaxCall(call_url, "GET", null);
    };

단계별 과정을 완료한 경우: 플레이어 생성 및 게시와 같은 일부 프로세스에는 여러 API 호출이 필요하다는 것을 알고있는 플레이어 관리 문서입니다. 또한 일부 앱의 논리에는 표시 할 모든 플레이어 목록을 가져온 다음 사용자가 표시 한 플레이어를 삭제하는 등 여러 API 호출이 필요할 수 있습니다. 이러한 경우에는 방금 성공적으로 수행된 호출에 따라 다른 로직을 수행하도록success핸들러를 변경해야 할 가능성이 높습니다. 이러한 샘플 앱에서 이러한 사용 사례에 대한 구현 논리는 플래그 변수를 사용하여 구현됩니다. callPurpose , 그리고case다음과 같이 해당 플래그를 사용하는 명령문:

    var ajaxSuccess = function (data) {
        switch (callPurpose) {
            case "getPlayers":
                createCheckboxes(data);
                watchCheckboxes();
                break;
            case "deletePlayer":
                document.getElementById("jsonResponse").textContent += data;
                break;
        }
    };

제이쿼리가 없는 아약스

jQuery를 사용하지 않으려면 AJAX 요청을 만드는 것이 조금 더 복잡하지만 너무 많지는 않습니다. 다음은 시작을위한 주석과 함께 몇 가지 샘플 코드입니다.

    /**
     * createRequest sets up requests, send them to makeRequest(), and handles responses
     * @param  {string} type the request type
     */
    function createRequest(type) {
        var options   = {},
            baseURL = 'https://players.api.brightcove.com/v2/accounts/',
            account_id = '1234567890',
            // would be better to get these from form fields
            // and not hardcode them
            username = 'jane@myplace.com',
            password = 'mypassword',
            responseDecoded;
    
        // set credentials
        options.client_id     = cid.value;
        options.client_secret = secret.value;
    
        switch (type) {
            case 'getPlayers':
                options.url         = ipBaseURL + account_id + '/players';
                options.requestType = 'GET';
                options.username = username;
                options.password = password;
                makeRequest(options, function(response) {
                    // use try catch in case something went wrong
                    try {
                        responseDecoded = JSON.parse(response);
                        // now do whatever you want with the response
                    }
                    catch (e) {
                        console.log('something went wrong - this was the JSON.parse error: ' + e);
                    }
                });
                break;
            // additional cases
            default:
                console.log('Should not be getting to the default case - bad request type sent');
                break;
        }
    }
    
    /**
     * send API request
     * @param  {Object} options for the request
     * @param  {String} options.url the full API request URL
     * @param  {String="GET","POST","PATCH","PUT","DELETE"} requestData [options.requestType="GET"] HTTP type for the request
     * @param  {String} options.username username for the account
     * @param  {String} options.password password for the account
     * @param  {JSON} [options.requestBody] Data (if any) to be sent in the request body in the form of a JSON string
     * @param  {Function} [callback] callback function that will process the response
     */
    function makeRequest(options, callback) {
        var httpRequest = new XMLHttpRequest(),
            response,
            requestParams,
            dataString,
            // response handler
            getResponse = function() {
                try {
                    if (httpRequest.readyState === 4) {
                        // don't just check for status = 200
                        // some requests return other 2xx codes
                        if (httpRequest.status >= 200 && httpRequest.status < 300) {
                            response = httpRequest.responseText;
                            // return the response to the callback
                            callback(response);
                        } else {
                            alert('There was a problem with the request. Request returned ' + httpRequest.status);
                        }
                    }
                } catch (e) {
                    alert('Caught Exception: ' + e);
                }
            };
        /**
         * set up request data
         */
        // set response handler
        httpRequest.onreadystatechange = getResponse;
        // open the request
        httpRequest.open(options.requestType, options.url);
        // set headers
        httpRequest.setRequestHeader("Content-Type", "application/json");
        httpRequest.setRequestHeader("Authorization", "Basic " + btoa(options.username + ":" + options.password));
        // open and send request
        if (options.requestBody) {
            httpRequest.send(options.requestBody)
        } else {
            httpRequest.send();
        }
    }