Skip to content

Commit

Permalink
feat(network): support array params (#4563)
Browse files Browse the repository at this point in the history
  • Loading branch information
wzhudev authored Jan 24, 2025
1 parent 2683655 commit 043aedc
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
40 changes: 40 additions & 0 deletions packages/network/src/services/http/__testing__/http-params.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Copyright 2023-present DreamNum Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { describe, expect, it } from 'vitest';
import { HTTPParams } from '../params';

describe('test class HTTPParams', () => {
it('should support empty params', () => {
const params = new HTTPParams();
expect(params.toString()).toBe('');
});

it('should support single params', () => {
const params = new HTTPParams({ key: 'value' });
expect(params.toString()).toBe('key=value');
});

it('should support multiple params', () => {
const params = new HTTPParams({ key1: 'value1', key2: 'value2' });
expect(params.toString()).toBe('key1=value1&key2=value2');
});

it('should support array params', () => {
const params = new HTTPParams({ key: ['value1', 'value2'] });
expect(params.toString()).toBe('key=value1&key=value2');
});
});
15 changes: 13 additions & 2 deletions packages/network/src/services/http/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
* limitations under the License.
*/

type ValidParamType = string | number | boolean;

export class HTTPParams {
constructor(readonly params?: { [key: string]: string | number | boolean }) {
constructor(readonly params?: { [key: string]: ValidParamType | ValidParamType[] }) {
// empty
}

Expand All @@ -25,7 +27,16 @@ export class HTTPParams {
}

return Object.keys(this.params)
.map((key) => `${key}=${this.params![key]}`)
.map((key) => {
const value = this.params![key];
if (Array.isArray(value)) {
return value
.map((v) => `${key}=${v}`)
.join('&');
}

return `${key}=${value}`;
})
.join('&');
}
}

0 comments on commit 043aedc

Please sign in to comment.