guide在 Node.js 中创建环境

本文介绍了使用 Cloud Services Management REST API 在 Node.js 中创建环境的示例。

此示例仅适用于本地部署版本。

# 依赖项

此示例使用 request-promise-native 和 Node.js 的核心依赖项:cryptourl

# 示例

以下简单示例展示了如何使用 Cloud Services Management REST API 创建环境。
ENVIRONMENTS_MANAGEMENT_SECRET_KEYAPPLICATION_ENDPOINT 变量应设置为来自配置的正确值。

const url = require( 'url' );
const crypto = require( 'crypto' );
const requestPromise = require( 'request-promise-native' );

const ENVIRONMENTS_MANAGEMENT_SECRET_KEY = 'secret';
const APPLICATION_ENDPOINT = 'https://127.0.0.1:8000';

( async () => {
    try {
        const newEnvironment = {
            id: _randomString( 20 ), // required length 20
            name: 'Production',
            organizationId: _randomString( 60 ), // required length 10-60
            accessKeys: [
                {
                    value: _randomString( 100 ) // required length 10-120
                }
            ],
            services: [
                {
                    id: _randomString( 24 ), // required length 24
                    type: 'easy-image'
                },
                {
                    id: _randomString( 24 ), // required length 24
                    type: 'collaboration'
                }
            ] // all these services types recommended
        };

        const timestamp = Date.now();

        const uri = `${ APPLICATION_ENDPOINT }/environments`;
        const method = 'POST';

        const signature = _generateSignature(
            ENVIRONMENTS_MANAGEMENT_SECRET_KEY,
            method,
            uri,
            timestamp,
            newEnvironment
        );

        const options = {
            uri,
            method,
            headers: {
                'X-CS-Signature': signature,
                'X-CS-Timestamp': timestamp
            },
            body: newEnvironment,
            json: true,
            rejectUnauthorized: false // required for domains with self signed certificate
        };

        await requestPromise( options );

        console.log( 'New Environment created.' );
        console.log( `EnvironmentId: ${ newEnvironment.id } AccessKey: ${ newEnvironment.accessKeys[ 0 ].value }` );
    } catch ( error ) {
        console.log( 'error:', error.message );
    }
} )();

function _generateSignature( apiSecret, method, uri, timestamp, body ) {
    const path = url.parse( uri ).path;

    const hmac = crypto.createHmac( 'SHA256', apiSecret );

    hmac.update( `${ method.toUpperCase() }${ path }${ timestamp }` );

    if ( body ) {
        hmac.update( Buffer.from( JSON.stringify( body ) ) );
    }

    return hmac.digest( 'hex' );
}

function _randomString( length ) {
    return crypto.randomBytes( length / 2 ).toString( 'hex' );
}

# 用法

运行

node index.js