Skip to content

Commit

Permalink
Added utility to handle various body formats (#14)
Browse files Browse the repository at this point in the history
* added utility to handle various body formats

* fixed typos
  • Loading branch information
raygesualdo authored and zackify committed Dec 21, 2016
1 parent 58d77ac commit 2bd431d
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 2 deletions.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"babel-preset-latest": "^6.16.0",
"babel-register": "^6.18.0",
"chai": "^3.5.0",
"form-data": "^2.1.2",
"mocha": "^3.2.0",
"standard": "^8.6.0"
},
Expand All @@ -43,7 +44,8 @@
"globals": [
"describe",
"it",
"expect"
"expect",
"FormData"
]
}
}
14 changes: 14 additions & 0 deletions src/utilities/body.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export default (body) => {
// Handle empty case
if (!body) return null
// Handle FormData
if (body instanceof FormData) return body
try {
// Handle already stringified JSON
JSON.parse(body)
return body
} catch (err) {
// Handle plain object
return JSON.stringify(body)
}
}
4 changes: 3 additions & 1 deletion src/utilities/normalize.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import processBody from './body'

/*
Take in raw query string and
return a fetch api compatible object
Expand Down Expand Up @@ -45,7 +47,7 @@ export default (strings, vars) => {
url,
options: {
method: method || 'GET',
body: body ? JSON.stringify(body) : null,
body: processBody(body),
...options
}
}
Expand Down
2 changes: 2 additions & 0 deletions tests/setup.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import 'babel-polyfill'
import FormData from 'form-data'
import { expect } from 'chai'

global.expect = expect
global.FormData = FormData
32 changes: 32 additions & 0 deletions tests/unit/body.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import processBody from '../../src/utilities/body'

describe('processBody', () => {
it('returns null when no value is passed', () => {
const body = processBody()
expect(body).to.equal(null)
})

it('returns null when empty string is passed', () => {
const body = processBody('')
expect(body).to.equal(null)
})

it('returns input when FormData is passed', () => {
const fd = new FormData()
const body = processBody(fd)
expect(body).to.equal(fd)
})

it('returns input when stringified data is passed', () => {
const data = JSON.stringify({value: 'test'})
const body = processBody(data)
expect(body).to.equal(data)
})

it('returns stringified data when object is passed', () => {
const rawData = {value: 'test'}
const data = JSON.stringify(rawData)
const body = processBody(rawData)
expect(body).to.equal(data)
})
})

0 comments on commit 2bd431d

Please sign in to comment.