Skip to content

Commit bb24daf

Browse files
committed
arrayRequestBody helper
1 parent b62ee71 commit bb24daf

File tree

5 files changed

+31
-3
lines changed

5 files changed

+31
-3
lines changed

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,4 +179,15 @@ type Ret = FetchReturnType<typeof findPetsByStatus>
179179
type Err = FetchErrorType<typeof findPetsByStatus>
180180
```
181181
182+
### Utility Methods
183+
184+
- `arrayRequestBody` - Helper to merge params when request body is an array
185+
186+
```ts
187+
188+
const body = arrayRequestBody([{ item: 1}], { param: 2})
189+
190+
// body type is { item: number }[] & { param: number }
191+
```
192+
182193
Happy fetching! 👍

src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Fetcher } from './fetcher'
2+
import { arrayRequestBody } from './utils'
23

34
import type {
45
ApiResponse,
@@ -28,4 +29,4 @@ export type {
2829
TypedFetch,
2930
}
3031

31-
export { Fetcher, ApiError }
32+
export { Fetcher, ApiError, arrayRequestBody }

src/utils.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/**
2+
* Helper to merge params when request body is an array
3+
*/
4+
export function arrayRequestBody<T, O>(array: T[], params?: O): T[] & O {
5+
return Object.assign([...array], params)
6+
}

test/fetch.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import 'whatwg-fetch'
22

33
import { server } from './mocks/server'
4-
import { ApiError, Fetcher } from '../src'
4+
import { ApiError, arrayRequestBody, Fetcher } from '../src'
55
import { Data, paths } from './paths'
66

77
beforeAll(() => server.listen())
@@ -68,7 +68,7 @@ describe('fetch', () => {
6868
it(`${method.toUpperCase()} /bodyarray/{id}`, async () => {
6969
const fun = fetcher.path('/bodyarray/{id}').method(method).create()
7070

71-
const { data } = await fun(Object.assign(['b', 'c'], { id: 1 }))
71+
const { data } = await fun(arrayRequestBody(['b', 'c'], { id: 1 }))
7272

7373
expect(data.params).toEqual({ id: '1' })
7474
expect(data.body).toEqual(['b', 'c'])

test/utils.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { arrayRequestBody } from '../src'
2+
3+
describe('utils', () => {
4+
it('array request body with params', () => {
5+
const body = arrayRequestBody([{ item: 2 }], { param: 3 })
6+
expect(body.length).toEqual(1)
7+
expect(body[0].item).toEqual(2)
8+
expect(body.param).toEqual(3)
9+
})
10+
})

0 commit comments

Comments
 (0)