Skip to content
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

allow skipping JSON coercion of request body #51

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,12 @@
"abort-controller": "^3.0.0",
"apollo-datasource-rest": "^3.5.1",
"ava": "^3.15.0",
"form-data": "^4.0.0",
"graphql": "^16.3.0",
"h2url": "^0.2.0",
"nock": "^13.2.4",
"nyc": "^15.1.0",
"parse-multipart-data": "^1.4.0",
"prettier": "^2.5.1",
"release-it": "^14.12.4",
"ts-node": "^10.5.0",
Expand Down
9 changes: 7 additions & 2 deletions src/http-data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ export type Request<T = unknown> = {
query: Dictionary<string | number>
body: T
signal?: AbortSignal | EventEmitter | null
/**
* Skips JSON.stringify coersion of Request.body
*/
json?: boolean
origin: string
path: string
Expand Down Expand Up @@ -299,8 +302,10 @@ export abstract class HTTPDataSource<TContext = any> extends DataSource {
cacheKey: string,
): Promise<Response<TResult>> {
try {
// in case of JSON set appropriate content-type header
if (request.body !== null && typeof request.body === 'object') {
if (request.json === false) {
// skip coercing to json
} else if (request.body !== null && typeof request.body === 'object') {
// in case of JSON set appropriate content-type header
if (request.headers['content-type'] === undefined) {
request.headers['content-type'] = 'application/json; charset=utf-8'
}
Expand Down
69 changes: 68 additions & 1 deletion test/http-data-source.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import anyTest, { TestInterface } from 'ava'
import http from 'http'
import { createGzip, createDeflate, createBrotliCompress } from 'zlib'
import { Readable } from 'stream';
import { Readable } from 'stream'
import { setGlobalDispatcher, Agent, Pool } from 'undici'
import FormData from 'form-data'
import { parse } from 'parse-multipart-data'
import AbortController from 'abort-controller'
import querystring from 'querystring'
import { HTTPDataSource, Request, Response, RequestError } from '../src'
Expand Down Expand Up @@ -147,6 +149,71 @@ test('Should be able to make a simple POST with JSON body', async (t) => {
t.deepEqual(response.body, { name: 'foo' })
})

test('Should be able to make a simple POST with FormData body', async (t) => {
t.plan(5)

const path = '/'

const wanted = { name: 'foo' }

const server = http.createServer((req, res) => {
const contentType = req.headers['content-type']
t.is(req.method, 'POST')
t.truthy(contentType)
t.regex(
// @ts-expect-error asserting truthy above
contentType,
/multipart\/form\-data/,
)

let raw = ''

req.on('data', (chunk) => {
raw += chunk
})
req.on('end', () => {
const data = parse(
Buffer.from(raw),
// @ts-expect-error asserting truthy above
contentType.replace('multipart/form-data; boundary=', ''),
).map((part) => ({ name: part.name, data: part.data.toString('utf8') }))

t.deepEqual(data, [{ name: 'foo', data: 'bar' }])
res.writeHead(200, {
'content-type': 'application/json',
})
res.write(JSON.stringify(wanted))
res.end()
res.socket?.unref()
})
})

t.teardown(server.close.bind(server))

server.listen()

const baseURL = getBaseUrlOf(server)

const dataSource = new (class extends HTTPDataSource {
constructor() {
super(baseURL)
}
postFoo() {
const form = new FormData()
form.append('foo', 'bar')
return this.post(path, {
headers: form.getHeaders(),
json: false,
body: form.getBuffer(),
})
}
})()

const response = await dataSource.postFoo()

t.deepEqual(response.body, { name: 'foo' })
})

test('Should be able to make a simple DELETE call', async (t) => {
t.plan(2)

Expand Down