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.
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 --saveInitialize 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:
You can obtain the
spaceIdandendpointafter you create a service space in the EMAS Serverless console. For more information, see Create your first service space.You can obtain
serverSecretby calling the DescribeSpaceClientConfig operation.
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); }NoteError handling:
Use a try/catch block to catch call errors.
The caught error object contains the error.name and error.message fields.