The HuaweiCloud Node.js SDK allows you to easily work with Huawei Cloud services such as Elastic Compute Service (ECS) and Virtual Private Cloud (VPC) without the need to handle API related tasks.
This document introduces how to obtain and use HuaweiCloud Node.js SDK.
-
Import the required modules as follows
// User identity authentication
import { BasicCredentials } from "@huaweicloud/huaweicloud-sdk-core/auth/BasicCredentials";
import { GlobalCredentials } from "@huaweicloud/huaweicloud-sdk-core/auth/GlobalCredentials";
// {Service}Client, replace Devstar to your specified service, take DevStarClient for example
import { DevStarClient } from "@huaweicloud/huaweicloud-sdk-devstar/v1/DevStarClient";
// Import the corresponding product model
import { ShowJobDetailRequest } from '@huaweicloud/huaweicloud-sdk-devstar/v1/model/ShowJobDetailRequest';
-
Config the {Service}Client
configurations
2.1 Use default configuration
// Use default configuration
const client = DevStarClient.newBuilder()
2.2 Proxy(Optional)
// Use proxy if needed
client.withProxyAgent("http://username:password@proxy.huaweicloud.com")
2.3 SSL Certification(Optional)
// Skip ssl certification checking while using https protocol if needed
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
-
Initialize Credentials
3.1 Use permanent AK/SK
// Regional Services
const basicCredentials = new BasicCredentials()
.withAk('ak')
.withSk('sk')
.withProjectId('projectId')
// Global Services
const globalCredentials = new GlobalCredentials()
.withAk('ak')
.withSk('sk')
.withDomainId('domainId')
where:
For project services, you only need to provide projectId, domainId is optional. While using global services, projectId must be null, and domainId should be filled in according to the actual situation. Global services only contains IAM(Identity and Access Management) currently.
ak
is the access key ID for your account.sk
is the secret access key for your account.projectId
is the ID of your project depending on your region which you want to operate.domainId
is the account ID of huawei cloud.
3.2 Use temporary AK/SK
It's preferred to obtain temporary access key, security key and security token first, which could be obtained through permanent access key and security key or through an agency.
Obtaining a temporary access key token through permanent access key and security key, you could refer to document: https://support.huaweicloud.com/en-us/api-iam/iam_04_0002.html . The API mentioned in the document above corresponds to the method of createTemporaryAccessKeyByToken in IAM SDK.
Obtaining a temporary access key and security token through an agency, you could refer to document: https://support.huaweicloud.com/en-us/api-iam/iam_04_0101.html . The API mentioned in the document above corresponds to the method of createTemporaryAccessKeyByAgency in IAM SDK.
// Region级服务
const basicCredentials = new BasicCredentials()
.withAk('ak')
.withSk('sk')
.withSecurityToken('securityToken')
.withProjectId('projectId')
// Global级服务
const globalCredentials = new GlobalCredentials()
.withAk('ak')
.withSk('sk')
.withSecurityToken('securityToken')
.withDomainId('domainId')
-
Initialize the {Service}Client instance
const client = DevStarClient.newBuilder()
.withCredential(basicCredentials)
.withEndpoint(endpoint)
.withProxyAgent(proxy)
.build()
where:
-
Send a request and print response
const result = client.showJobDetail(new ShowJobDetailRequest("id"));
result.then(result => {
res.send("JSON.stringify(result)::" + JSON.stringify(result))
}).catch(ex => {
res.send("exception:" + JSON.stringify(ex))
});
-
Exceptions
Level 1 | Notice | Level 2 | Notice |
---|
ConnectionException | Connection error | HostUnreachableException | Host is not reachable |
| | SslHandShakeException | SSL certification error |
RequestTimeoutException | Request timeout | CallTimeoutException | timeout for single request |
| | RetryOutageException | no response after retrying |
ServiceResponseException | service response error | ServerResponseException | server inner error, http status code: [500,] |
| | ClientRequestException | invalid request, http status code: [400? 500) |
if (httpStatusCode >= 400 && httpStatusCode < 500) {
return new ClientRequestException(httpStatusCode, errorData);
} else if (httpStatusCode >= 500 && httpStatusCode < 600) {
return new ServerResponseException(httpStatusCode, errorData);
} else {
return new ServiceResponseException(httpStatusCode, errorData);
}
-
Access Log
The SDK will print the access log by default, every request will be recorded in console like:
16:53:04.905 [main] INFO HuaweiCloud-SDK-Access - "GET https://ecs.cn-southwest-2.myhuaweicloud.com/v1/077d6a6c19000fdd2f3bc00150080291/cloudservers/detail?offset=1&limit=25" 200 2251 deabe20c14f997a0291fc451a4da16a4
16:53:06.212 [main] INFO HuaweiCloud-SDK-Access - "PUT https://ecs.cn-southwest-2.myhuaweicloud.com/v1/077d6a6c19000fdd2f3bc00150080291/cloudservers/1aeac6fb-a2f2-48dc-9052-36637d119dd3" 200 880 f16f70e3fe245c11ab741760f8689a01
17:02:37.734 [main] INFO HuaweiCloud-SDK-Access - "GET https://ecs.cn-southwest-2.myhuaweicloud.com/v1/077d6a6c19000fdd2f3bc00150080291/cloudservers/detail?offset=1&limit=-1" 400 165 8c3c8b6fed4482d28e1929a78dc93f04
SDK access log name is "HuaweiCloud-SDK-Access", and out log format is:
"{httpMethod} {uri}" {httpStatusCode} {responseContentLength} {requestId}
Where:
requestId
is the ID returned by HuaweiCloud API Gateway, which can be used for user guarantee or issue tracking.
You can shield access log in the log configuration depending on your project, or print access log to an independent file.
-
Original HTTP Listener
In some situation, you may need to debug your http requests, original http request and response information will be needed. The SDK provides a listener function to obtain the original encrypted http request and response information.
:warning: Warning: The original http log information are used in debugging stage only, please do not print the original http header or body in the production environment. These log information are not encrypted and contain sensitive data such as the password of your ECS virtual machine or the password of your IAM user account, etc. When the response body is binary content, the body will be printed as "***" without detailed information.
Set the environment variable process.env.NODE_DEBUG or process.env.DEBUG to enable debug log printing.
if (process.env.NODE_DEBUG === 'axios' || process.env.DEBUG) {
this.axiosInstance.interceptors.request.use((config: any) => {
logger.debug('Request:');
try {
logger.debug(JSON.stringify(config, null, 2));
} catch {
logger.error(config)
}
return config;
}, (error: any) => {
logger.error('Error: ');
try {
logger.error(JSON.stringify(error, null, 2));
} catch {
logger.error(error);
}
// @ts-ignore
return Promise.reject(error);
});
this.axiosInstance.interceptors.response.use((response: any) => {
logger.debug('Response:');
try {
logger.debug(JSON.stringify(response, null, 2));
} catch {
logger.error(response);
}
return response;
}, (error: any) => {
logger.error('Error: ');
try {
logger.error(JSON.stringify(error, null, 2));
} catch {
logger.error(error);
}
// @ts-ignore
return Promise.reject(error);
});
}