Skip to content

Commit 98518d6

Browse files
committed
release 0.0.3-beta source code for nodejs
1 parent bdbf2a1 commit 98518d6

File tree

636 files changed

+24051
-680
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

636 files changed

+24051
-680
lines changed

CHANGELOG.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,23 @@
1+
# 0.0.3-beta 2023-01-06
2+
3+
### G42Cloud SDK IMS
4+
5+
- _Features_
6+
- New Support IMS
7+
- _Bug Fix_
8+
- None
9+
- _Change_
10+
- None
11+
12+
### G42Cloud SDK SMN
13+
14+
- _Features_
15+
- New Support SMN
16+
- _Bug Fix_
17+
- None
18+
- _Change_
19+
- None
20+
121
# 0.0.2-beta 2022-11-29
222

323
### G42Cloud SDK CSE

README.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<p align="center">
2-
<a href="https://www.g42cloud.com/"><img style="background-color:black;" width="450px" height="102px" src="https://auth.g42cloud.com//authui/20220614193554/public/custom/images/logo.svg"></a>
2+
<a href="https://www.g42cloud.com/"><img src="https://upload.wikimedia.org/wikipedia/en/4/43/Group_42_Logo.jpg"></a>
33
</p>
44

55
<h1 align="center">G42 Cloud Node.js Software Development Kit (Node.js SDK)</h1>
@@ -23,11 +23,11 @@ This document introduces how to obtain and use G42 Cloud Node.js SDK.
2323

2424
The recommended way to install SDK is with npm.
2525

26-
You must depended on `@huaweicloud/huaweicloud-sdk-core` library no matter which product/service development kit you
26+
You must depended on `@g42cloud/g42cloud-sdk-core` library no matter which product/service development kit you
2727
need to use. Take using VPC SDK for example, you need to install `@g42cloud/g42cloud-sdk-vpc` library:
2828

2929
``` bash
30-
npm install @huaweicloud/huaweicloud-sdk-core
30+
npm install @g42cloud/g42cloud-sdk-core
3131
npm install @g42cloud/g42cloud-sdk-vpc
3232
```
3333

@@ -39,8 +39,8 @@ npm install @g42cloud/g42cloud-sdk-vpc
3939

4040
``` javascript
4141
// index.js
42-
const core = require('@huaweicloud/huaweicloud-sdk-core');
43-
const vpc = require('@g42cloud/huaweicloud-sdk-vpc');
42+
const core = require('@g42cloud/g42cloud-sdk-core');
43+
const vpc = require('@g42cloud/g42cloud-sdk-vpc');
4444

4545
const ak = '<YOUR AK>';
4646
const sk = '<YOUR SK>';

core/.mocharc.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"require": [
3+
"ts-node/register",
4+
"source-map-support/register"
5+
],
6+
"timeout": 3000
7+
}

core/ClientBuilder.ts

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
/*
2+
* Copyright 2020 G42 Technologies Co.,Ltd.
3+
*
4+
* Licensed to the Apache Software Foundation (ASF) under one
5+
* or more contributor license agreements. See the NOTICE file
6+
* distributed with this work for additional information
7+
* regarding copyright ownership. The ASF licenses this file
8+
* to you under the Apache License, Version 2.0 (the
9+
* "License"); you may not use this file except in compliance
10+
* with the License. You may obtain a copy of the License at
11+
*
12+
* http://www.apache.org/licenses/LICENSE-2.0
13+
*
14+
* Unless required by applicable law or agreed to in writing,
15+
* software distributed under the License is distributed on an
16+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17+
* KIND, either express or implied. See the License for the
18+
* specific language governing permissions and limitations
19+
* under the License.
20+
*/
21+
22+
import { HcClient } from "./HcClient";
23+
import { ICredential } from "./auth/ICredential";
24+
import { ClientOptions, DefaultHttpClient } from "./http/DefaultHttpClient";
25+
import { RequiredError } from "./auth/AKSKSigner";
26+
import { BasicCredentials } from "./auth/BasicCredentials";
27+
import { GlobalCredentials } from "./auth/GlobalCredentials";
28+
import { SdkException } from "./exception/SdkException";
29+
import { Region } from "./region/region";
30+
import { UserOptions } from "./UserOptions";
31+
const path = require('path');
32+
33+
interface CredParams {
34+
ak?: string;
35+
sk?: string,
36+
project_id?: string,
37+
domain_id?: string,
38+
}
39+
export class ClientBuilder<T> {
40+
private init: Function;
41+
private endpoint?: string;
42+
private credential?: ICredential;
43+
private proxyAgent?: string;
44+
private credentialType: string[] = ["BasicCredentials", "GlobalCredentials"];
45+
private envParams: CredParams = process.env;
46+
private region?: Region;
47+
private userOptions?: UserOptions;
48+
49+
public constructor(init: (hcClient: HcClient) => T, credentialType?: string) {
50+
this.init = init;
51+
if (credentialType) {
52+
this.credentialType = credentialType.split(",");
53+
}
54+
}
55+
56+
public withEndpoint(endpoint: string): ClientBuilder<T> {
57+
this.endpoint = endpoint;
58+
return this;
59+
}
60+
61+
public withCredential(credential?: ICredential): ClientBuilder<T> {
62+
this.credential = credential;
63+
return this;
64+
}
65+
66+
public withProxyAgent(proxyAgent: string): ClientBuilder<T> {
67+
this.proxyAgent = proxyAgent;
68+
return this;
69+
}
70+
71+
public withRegion(region: Region): ClientBuilder<T> {
72+
this.region = region;
73+
return this;
74+
}
75+
76+
public withOptions(options: UserOptions): ClientBuilder<T> {
77+
this.userOptions = options;
78+
return this;
79+
}
80+
81+
public build(): T {
82+
const axiosOptions: ClientOptions = {
83+
disableSslVerification: true
84+
};
85+
if (this.proxyAgent) {
86+
Object.assign(axiosOptions, { proxy: this.proxyAgent });
87+
}
88+
if (this.userOptions?.customUserAgent) {
89+
axiosOptions.headers = axiosOptions.headers || {};
90+
axiosOptions.headers["User-Agent"] = this.userOptions.customUserAgent;
91+
}
92+
93+
if (!this.credential) {
94+
this.credential = this.getCredentialFromEnvironment();
95+
}
96+
97+
if (!this.credential) {
98+
throw new SdkException(`credential can not be null, ${this.credentialType}Credential objects are required`);
99+
}
100+
101+
const client = new DefaultHttpClient(axiosOptions);
102+
const hcClient = new HcClient(client);
103+
hcClient.withEndpoint(this.endpoint).withCredential(this.credential);
104+
if (this.region) {
105+
hcClient.withRegion(this.region);
106+
}
107+
return this.init(hcClient);
108+
}
109+
110+
/**
111+
* 从环境变量获取 HUAWEICLOUD_SDK_TYPE
112+
* 环境变量里没有则使用 credentialType[0]
113+
* 生成credential实体
114+
* 从环境变量获取 AK SK projectId/domainId 进行赋值, 如果环境变量是GlobalCredentials,则赋值domainId
115+
* @returns Credentials
116+
*/
117+
public getCredentialFromEnvironment(): ICredential {
118+
const sdkType: any = process.env.HUAWEICLOUD_SDK_TYPE;
119+
const credentialTYPE = this.whichCredential(sdkType)
120+
return this.getInputParamCredential(credentialTYPE, this.envParams);
121+
}
122+
123+
public whichCredential(sdkType: string) {
124+
let credentialTYPE;
125+
if (sdkType) {
126+
switch (sdkType) {
127+
case 'BasicCredentials':
128+
credentialTYPE = new BasicCredentials();
129+
break;
130+
case 'GlobalCredentials':
131+
credentialTYPE = new GlobalCredentials();
132+
break;
133+
default:
134+
const obj = {};
135+
const definedCredPath = path.join(this.init().getPath(), `${sdkType}`);
136+
if (!obj[sdkType]) {
137+
credentialTYPE = require(definedCredPath);
138+
// 多加一层
139+
obj[sdkType] = credentialTYPE[sdkType];
140+
}
141+
credentialTYPE = new obj[sdkType]();
142+
break;
143+
}
144+
} else {
145+
// 默认是basic
146+
credentialTYPE = new BasicCredentials();
147+
}
148+
return credentialTYPE;
149+
}
150+
151+
public getInputParamCredential(CredentialsType: any, credential: CredParams) {
152+
// 判断是否有_
153+
let hash = {};
154+
for (let key in credential) {
155+
if (key.indexOf("HUAWEICLOUD_SDK_") == 0) {
156+
const value = credential[key]
157+
key = key.substring(16);
158+
if (key.indexOf('_') == -1) {
159+
key = key.toLowerCase();
160+
key = 'with' + key.charAt(0).toUpperCase() + key.slice(1);
161+
} else {
162+
const arr = key.split('_').map(item => {
163+
item = item.toLowerCase();
164+
return item.charAt(0).toUpperCase() + item.slice(1);
165+
})
166+
if (Array.isArray(arr)) {
167+
key = 'with' + arr.join("");
168+
}
169+
}
170+
hash[key] = value
171+
}
172+
}
173+
credential = hash;
174+
for (const key in credential) {
175+
if (CredentialsType[key]) {
176+
CredentialsType[key](credential[key]);
177+
}
178+
}
179+
return CredentialsType;
180+
}
181+
182+
}

core/HcClient.ts

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
/*
2+
* Copyright 2020 G42 Technologies Co.,Ltd.
3+
*
4+
* Licensed to the Apache Software Foundation (ASF) under one
5+
* or more contributor license agreements. See the NOTICE file
6+
* distributed with this work for additional information
7+
* regarding copyright ownership. The ASF licenses this file
8+
* to you under the Apache License, Version 2.0 (the
9+
* "License"); you may not use this file except in compliance
10+
* with the License. You may obtain a copy of the License at
11+
*
12+
* http://www.apache.org/licenses/LICENSE-2.0
13+
*
14+
* Unless required by applicable law or agreed to in writing,
15+
* software distributed under the License is distributed on an
16+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17+
* KIND, either express or implied. See the License for the
18+
* specific language governing permissions and limitations
19+
* under the License.
20+
*/
21+
22+
import { HttpClient } from "./http/HttpClient";
23+
import { ICredential } from "./auth/ICredential";
24+
import { IHttpRequest } from "./http/IHttpRequest";
25+
import { HttpRequestBuilder } from "./http/IHttpRequestBuilder";
26+
import { SdkResponse } from "./SdkResponse";
27+
import { ExceptionUtil } from "./exception/ExceptionUtil";
28+
import { getLogger, Logger, LogLevel } from './logger';
29+
import { DefaultHttpResponse } from "./http/DefaultHttpResponse";
30+
import { Region } from "./region/region";
31+
32+
export class HcClient {
33+
private httpClient: HttpClient;
34+
private endpoint: string | undefined;
35+
private credential: ICredential | undefined;
36+
private proxyAgent: string = '';
37+
private static loggerName = 'HcClient';
38+
private logger: Logger;
39+
region?: Region;
40+
41+
public constructor(client: HttpClient) {
42+
this.httpClient = client;
43+
44+
// Logging
45+
this.logger = getLogger(HcClient.loggerName, LogLevel.INFO);
46+
this.logger.debug('initialized');
47+
}
48+
49+
public withEndpoint(endpoint?: string): HcClient {
50+
this.endpoint = endpoint;
51+
return this;
52+
}
53+
54+
public withCredential(credential?: ICredential): HcClient {
55+
this.credential = credential;
56+
return this;
57+
}
58+
59+
public withRegion(region?: Region) {
60+
this.region = region;
61+
return this;
62+
}
63+
64+
public withHttpsAgent(proxyAgent: string) {
65+
this.proxyAgent = proxyAgent;
66+
return this;
67+
}
68+
public async sendRequest<T extends SdkResponse>(options: any): Promise<any> {
69+
this.logger.debug('send request');
70+
71+
const request = await this.buildRequest(options);
72+
// @ts-ignore
73+
return this.httpClient.sendRequest<T>(request).then(res => {
74+
return this.extractResponse<T>(res);
75+
}, err => {
76+
return ExceptionUtil.generalException(err);
77+
});
78+
}
79+
80+
private async buildRequest(options: any): Promise<IHttpRequest> {
81+
if (this.region) {
82+
this.endpoint = this.region.endpoint;
83+
this.credential = await this.credential!.processAuthParams(this, this.region.id);
84+
}
85+
86+
let url = this.endpoint + options.url;
87+
const pathParams = options.pathParams;
88+
Object.keys(pathParams).forEach(x => {
89+
url = url.replace("{" + x + "}", pathParams[x]);
90+
});
91+
92+
if (options.method === 'DELETE'
93+
&& (options.data && (Object.keys(options.data).length <= 0 || options.data.length <= 0))) {
94+
delete options.data;
95+
}
96+
97+
if (options.headers && Object.prototype.hasOwnProperty.call(options.headers, "Content-Type")) {
98+
delete options.headers['Content-Type'];
99+
}
100+
101+
if (options.contentType) {
102+
if (!options.headers) {
103+
options.headers = {};
104+
}
105+
if (options.contentType.toLowerCase().startsWith("application/json")) {
106+
// remove charset
107+
options.headers['content-type'] = "application/json";
108+
} else {
109+
options.headers['content-type'] = options.contentType;
110+
}
111+
}
112+
113+
const builder = new HttpRequestBuilder();
114+
let httpRequest = builder
115+
.withEndpoint(url)
116+
.withHeaders(options.headers)
117+
.withMethod(options.method)
118+
.withPathParams(options.pathParams)
119+
.withData(options.data)
120+
.withQueryParams(options.queryParams)
121+
.build();
122+
123+
// @ts-ignore
124+
httpRequest = this.credential.processAuthRequest(httpRequest);
125+
if (options['responseHeaders']) {
126+
httpRequest['responseHeaders'] = options['responseHeaders'];
127+
}
128+
httpRequest.proxy = this.proxyAgent;
129+
return httpRequest;
130+
}
131+
132+
private extractResponse<T extends SdkResponse>(result: DefaultHttpResponse<T>): T {
133+
const headers = result.headers;
134+
let contentType = headers['content-type'];
135+
contentType = contentType.toLowerCase();
136+
if (contentType && (contentType.startsWith('application/octet-stream') || contentType.startsWith("image"))) {
137+
return result.data as T;
138+
} else {
139+
let response = result.data instanceof Object ? result.data : {} as T;
140+
let sdkRespone = response as SdkResponse;
141+
sdkRespone.httpStatusCode = result.statusCode;
142+
143+
return response;
144+
}
145+
}
146+
}

0 commit comments

Comments
 (0)