다음을 통해 공유


CloudScript의 ES6 기능

CloudScript 런타임 환경은 최신 ECMAScript 6 기능 대부분을 지원합니다. 이러한 기능 중 대다수는 구문 트릭이지만 CloudScript 코드를 개선하고 정리하는 데 사용할 수 있습니다.

ES6 기능에 대한 전체 개요가 이 치트 시트에 있습니다.

이 자습서에서는 CloudScript에서 사용할 수 있는 몇 가지 트릭을 보여줍니다.

참고 항목

일부 기능에는 strict 모드가 필요합니다. 다음 코드를 CloudScript 파일의 맨 첫 번째 줄에 배치하여 이 모드를 활성화합니다. use strict;

문자열 보간

플레이어를 위한 메시지를 작성할 때는 여러 줄이 보간된 문자열을 사용하는 것이 좋습니다. 보간된 문자열을 만들려면 백틱 기호를 사용합니다. 그러면 ${ variable } 구문을 사용하여 데이터를 바로 문자열에 삽입할 수 있습니다.

따라서 문자열 연결을 피하고 코드 가독성을 향상할 수 있습니다.

참고 항목

백틱 문자열은 축자이며 여러 줄일 수 있습니다. 즉, 문자열에 추가 공간/탭이 캡처되므로 모든 들여쓰기를 주시해야 합니다.

function sendPushNotification(playerName, prizeAmount, newLevel) {
    let message = `Congratulations ${playerName}!
You have reached level ${newLevel}.
You get ${prizeAmount} coins for your efforts.`;
    // Use message variable and send push notification
    // ...
}

새 메서드 및 화살표 함수

ES6는 화살표 연산자 =>을(를) 사용하여 함수를 정의하는 새로운 구문을 도입합니다. 아래에 표시된 조각은 특정 연산자 사용을 위한 대략적인 번역을 표시합니다.

// The following snippets:
const add = (a,b) => a+b;

const add = (a,b) => {
    return a+b;
}

// Both translate into something like
function add(a, b) {
    return a+b;
}

이 연산자는 새 Array.findIndex 메서드와 결합되어 다음과 같이 보기 좋은 간결한 코드를 사용하여 조건자로 검색이 가능해집니다.

const players = [...]; // Suppose this is an array of Player Profiles

// Search by predicate: find item in 'players' that has 'DisplayName' set to 'Bob':
const bobIndex = players.findIndex(p => p.DisplayName === 'Bob');

개체 할당

Object.assign 메서드를 사용하여 새로운 집합의 속성 및 메서드로 개체를 쉽게 확장할 수 있습니다.

다양한 용도로 사용되는 이 메서드는 처리기 개체를 확장하고 처리기 그룹을 만들 때 특히 유용합니다.

let TestHandlers = {
    TestLeaderboards : (args, ctx) => {
        // Test leaderboards code
    },
    TestPrizes : (args, ctx) => {
        // Test prizes code
    }
    // ...
}

let ProductionHandlers = {
    CleanUp : (args, ctx) => {
        // System clean up code
    },
    GrantTournamentAccess : (args, ctx) => {
        // Another useful production code
    }
    // ...
}

// Install both handler groups:
Object.assign(handlers, TestHandlers);
Object.assign(handlers, ProductionHandlers);

// Comment out the group to disable it but keep the relevant code
// Object.assign(handlers, SomeOtherHandlers);

따라서 처리기 그룹을 신속하게 사용 및 사용 중지할 수 있을 뿐만 아니라 처리기를 처리하고 예외 처리와 같은 유용한 코드로 래핑할 수도 있습니다.

다음 코드는 이전 조각을 자동 예외 로깅으로 확장합니다. 예를 들어 문제를 기록하지만(항상 유용한 것은 아님) 취향에 맞게 동작을 확장할 수 있습니다.

// Handlers installer wraps the handler to catch error
function installHandlers(handlersObject) {
    for (let property in handlersObject) {
        handlersObject[property] = wrapHandler(handlersObject,property)
    }
    Object.assign(handlers, handlersObject);
}

// Utility
function wrapHandler(obj, key) {
    if (obj.hasOwnProperty(key) && typeof obj[key] === 'function') {
        let original = obj[key]; // Take the original function
        return function() { // return a new function that
            try { // Wraps the original invocation with try
                return original.apply(null,arguments); // Do not forget to pass arguments
            } catch (error) { // If error occurs
                log.error(error); // We log it, but you may want to retry / do something else
                throw error; // Rethrow to keep the original behaviour
            }
        }
    } else { // If property is not a function, ignore it
        return obj[key];
    }
}

// Install handler groups:
installHandlers(TestHandlers);
installHandlers(ProductionHandlers);

Getter

"Getter"를 사용하여 공통 API 호출을 구문 측면에서 더 만족스러운 디자인으로 캡슐화할 수 있습니다. 다음 타이틀 데이터 상태를 고려하세요.

게임 관리자 - 타이틀 데이터

다음 조각은 TitleData에서 FooBar 데이터를 검색한 다음 매우 간단하게 사용하는 방법을 보여줍니다.

'use strict'

// Define
let App = {
    get TitleData() {
        // Please, consider limiting the query by defining certain keys that you need
        return server.GetTitleData({}).Data;
    },
}

// Use
handlers.TestFooBar = () => {
    // Client code is clean and does not show the fact of calling any functions / making api request
    var titleData = App.TitleData; // Note that this implementation makes an API call every time it's accessed
    log.debug(titleData.Foo);
    log.debug(titleData.Bar);
}