v1.1.0: feat() enable uri encode for GET requests by default. add env var for tracing http requests.

This commit is contained in:
Tiago Siebler
2023-04-25 14:38:29 +01:00
parent b21d513777
commit 701f267d81
6 changed files with 129 additions and 20 deletions

View File

@@ -26,11 +26,12 @@ interface UnsignedRequest<T extends object | undefined = {}> {
type SignMethod = 'bitget';
if (
const ENABLE_HTTP_TRACE =
typeof process === 'object' &&
typeof process.env === 'object' &&
process.env.BITGETTRACE
) {
process.env.BITGETTRACE;
if (ENABLE_HTTP_TRACE) {
axios.interceptors.request.use((request) => {
console.log(
new Date(),
@@ -91,6 +92,7 @@ export default abstract class BaseRestClient {
recvWindow: 5000,
/** Throw errors if any request params are empty */
strictParamValidation: false,
encodeQueryStringValues: true,
...restOptions,
};
@@ -166,7 +168,9 @@ export default abstract class BaseRestClient {
isPublicApi,
);
// console.log('full request: ', options);
if (ENABLE_HTTP_TRACE) {
console.log('full request: ', options);
}
// Dispatch request
return axios(options)
@@ -250,11 +254,17 @@ export default abstract class BaseRestClient {
// It's possible to override the recv window on a per rquest level
const strictParamValidation = this.options.strictParamValidation;
const encodeQueryStringValues = this.options.encodeQueryStringValues;
if (signMethod === 'bitget') {
const signRequestParams =
method === 'GET'
? serializeParams(data, strictParamValidation, '?')
? serializeParams(
data,
strictParamValidation,
encodeQueryStringValues,
'?',
)
: JSON.stringify(data) || '';
const paramsStr =

View File

@@ -17,6 +17,13 @@ export interface RestClientOptions {
/** Default: false. If true, we'll throw errors if any params are undefined */
strictParamValidation?: boolean;
/**
* Default: true.
* If true, query string values will be URI Encoded (encodeURIComponent).
* This prevents sign errors with GET requests containing unusual parameters (spaces, symbols, etc).
*/
encodeQueryStringValues?: boolean;
/**
* Optionally override API protocol + domain
* e.g baseUrl: 'https://api.bitget.com'
@@ -30,6 +37,7 @@ export interface RestClientOptions {
export function serializeParams<T extends object | undefined = {}>(
params: T,
strict_validation = false,
encodeValues: boolean = true,
prefixWith: string = '',
): string {
if (!params) {
@@ -45,7 +53,8 @@ export function serializeParams<T extends object | undefined = {}>(
'Failed to sign API request due to undefined parameter',
);
}
return `${key}=${value}`;
const encodedValue = encodeValues ? encodeURIComponent(value) : value;
return `${key}=${encodedValue}`;
})
.join('&');