Skip to content

version 1.1.3 #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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