Install the Node.js client SDK

更新时间:
复制 MD 格式

This topic describes how to integrate the EMAS Serverless Node.js software development kit (SDK) to access EMAS Serverless services from a Node.js project.

Prerequisites

Before you use EMAS Serverless for the first time, you must activate the EMAS service. For more information, see the "Activate EMAS" section in Quick Start.

  1. Install the SDK. Run the following command in the root directory of your Node.js project.

    npm install @alicloud/mpserverless-node-sdk@1.2.3 --save
  2. Initialize the SDK. Add the following SDK initialization code to your project.

    // Reference the SDK
    const MPServerless = require('@alicloud/mpserverless-node-sdk').default;
    // Initialize the SDK
    const client = new MPServerless({
      	timeout: 60 * 1000,
        spaceId: 'mp-db4dd657-7041-470a-90xxxxx',
        endpoint: 'https://api.next.bspapp.com',
        serverSecret: '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhki******G9w0BAQE7V0sQaj\n-----END PRIVATE KEY-----',
    });

    Where:

  3. Call the SDK. The following code provides an example of calling the EMAS Serverless SDK in Node.js. For more information, see Cloud Function API documentation and Data Storage API documentation.

    // Cloud function
    try {
      const res = await client.function.invoke('testFunction');
      console.log('function invoke result: ', res);
    } catch (err) {
      console.log('function invoke error: ', err);
    }
    // Cloud database
    try {
      const res = await client.db.collection('testTable').count({});
      console.log('db service result: ', res);
    } catch (err) {
      console.log('db service error: ', err);
    }
    Note

    Error handling:

    • Use a try/catch block to catch call errors.

    • The caught error object contains the error.name and error.message fields.