Skip to content

Commit

Permalink
Merge pull request #29 from ajaishankar/develop
Browse files Browse the repository at this point in the history
version 1.1.3
  • Loading branch information
ajaishankar committed May 14, 2022
2 parents 8aecdf6 + dc1bdc5 commit 2e0d66e
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 11 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -181,7 +181,7 @@ type Err = FetchErrorType<typeof findPetsByStatus>
### Utility Methods
- `arrayRequestBody` - Helper to merge params when request body is an array
- `arrayRequestBody` - Helper to merge params when request body is an array [see issue](https://github.com/ajaishankar/openapi-typescript-fetch/issues/3#issuecomment-952963986)
```ts

Expand Down
2 changes: 1 addition & 1 deletion package.json
@@ -1,7 +1,7 @@
{
"name": "openapi-typescript-fetch",
"description": "A typed fetch client for openapi-typescript",
"version": "1.1.2",
"version": "1.1.3",
"engines": {
"node": ">= 12.0.0",
"npm": ">= 7.0.0"
Expand Down
13 changes: 8 additions & 5 deletions src/fetcher.ts
Expand Up @@ -72,10 +72,10 @@ function getQuery(
return queryString(queryObj)
}

function getHeaders(init?: HeadersInit) {
function getHeaders(body?: string, init?: HeadersInit) {
const headers = new Headers(init)

if (!headers.has('Content-Type')) {
if (body !== undefined && !headers.has('Content-Type')) {
headers.append('Content-Type', 'application/json')
}

Expand Down Expand Up @@ -120,21 +120,25 @@ function getFetchParams(request: Request) {

const path = getPath(request.path, payload)
const query = getQuery(request.method, payload, request.queryParams)
const headers = getHeaders(request.init?.headers)
const body = getBody(request.method, payload)
const headers = getHeaders(body, request.init?.headers)
const url = request.baseUrl + path + query

const init = {
...request.init,
method: request.method.toUpperCase(),
headers,
body: getBody(request.method, payload),
body,
}

return { url, init }
}

async function getResponseData(response: Response) {
const contentType = response.headers.get('content-type')
if (response.status === 204 /* no content */) {
return undefined
}
if (contentType && contentType.indexOf('application/json') !== -1) {
return await response.json()
}
Expand Down Expand Up @@ -179,7 +183,6 @@ function wrapMiddlewares(middlewares: Middleware[], fetch: Fetch): Fetch {
return fetch(url, init)
}
const current = middlewares[index]
init = init || { headers: getHeaders() }
return await current(url, init, (nextUrl, nextInit) =>
handler(index + 1, nextUrl, nextInit),
)
Expand Down
29 changes: 25 additions & 4 deletions test/fetch.test.ts
Expand Up @@ -24,10 +24,14 @@ describe('fetch', () => {

const expectedHeaders = {
authorization: 'Bearer token',
'content-type': 'application/json',
accept: 'application/json',
}

const headersWithContentType = {
...expectedHeaders,
'content-type': 'application/json',
}

it('GET /query/{a}/{b}', async () => {
const fun = fetcher.path('/query/{a}/{b}').method('get').create()

Expand Down Expand Up @@ -60,7 +64,7 @@ describe('fetch', () => {
expect(data.params).toEqual({ id: '1' })
expect(data.body).toEqual({ list: ['b', 'c'] })
expect(data.query).toEqual({})
expect(data.headers).toEqual(expectedHeaders)
expect(data.headers).toEqual(headersWithContentType)
})
})

Expand All @@ -73,7 +77,7 @@ describe('fetch', () => {
expect(data.params).toEqual({ id: '1' })
expect(data.body).toEqual(['b', 'c'])
expect(data.query).toEqual({})
expect(data.headers).toEqual(expectedHeaders)
expect(data.headers).toEqual(headersWithContentType)
})
})

Expand All @@ -93,10 +97,27 @@ describe('fetch', () => {
expect(data.params).toEqual({ id: '1' })
expect(data.body).toEqual({ list: ['b', 'c'] })
expect(data.query).toEqual({ scalar: 'a' })
expect(data.headers).toEqual(expectedHeaders)
expect(data.headers).toEqual(headersWithContentType)
})
})

it(`DELETE /body/{id} (empty body)`, async () => {
const fun = fetcher.path('/body/{id}').method('delete').create()

const { data } = await fun({ id: 1 } as any)

expect(data.params).toEqual({ id: '1' })
expect(data.headers).toHaveProperty('accept')
expect(data.headers).not.toHaveProperty('content-type')
})

it(`POST /nocontent`, async () => {
const fun = fetcher.path('/nocontent').method('post').create()
const { status, data } = await fun(undefined)
expect(status).toBe(204)
expect(data).toBeUndefined()
})

it('GET /error', async () => {
expect.assertions(3)

Expand Down
3 changes: 3 additions & 0 deletions test/mocks/handlers.ts
Expand Up @@ -64,6 +64,9 @@ const methods = {
)
: res(ctx.status(status))
}),
rest.post(`${HOST}/nocontent`, (req, res, ctx) => {
return res(ctx.status(204))
}),
rest.get(`${HOST}/defaulterror`, (req, res, ctx) => {
return res(ctx.status(500), ctx.body('internal server error'))
}),
Expand Down
8 changes: 8 additions & 0 deletions test/paths.ts
Expand Up @@ -61,6 +61,14 @@ export type paths = {
patch: BodyAndQuery
delete: BodyAndQuery
}
'/nocontent': {
post: {
parameters: {}
responses: {
204: unknown
}
}
}
'/error/{status}': {
get: {
parameters: {
Expand Down

0 comments on commit 2e0d66e

Please sign in to comment.