Skip to content

Commit

Permalink
Parse form encoded response body.
Browse files Browse the repository at this point in the history
  • Loading branch information
dgraham committed Oct 15, 2014
1 parent 2c1534a commit 60271ce
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
15 changes: 14 additions & 1 deletion fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
}

this.formData = function() {
throw new Error('Not implemented yet')
return Promise.resolve(decode(this.body))
}

this.json = function() {
Expand Down Expand Up @@ -115,6 +115,19 @@
}).join('&').replace(/%20/g, '+')
}

function decode(body) {
var form = new FormData()
body.trim().split('&').forEach(function(bytes) {
if (bytes) {
var split = bytes.split('=')
var name = split.shift().replace(/\+/g, ' ')
var value = split.join('=').replace(/\+/g, ' ')
form.append(decodeURIComponent(name), decodeURIComponent(value))
}
})
return form
}

function isObject(value) {
try {
return Object.getPrototypeOf(value) === Object.prototype
Expand Down
12 changes: 12 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ MockXHR.responses = {
'/error': function(xhr) {
xhr.error()
},
'/form': function(xhr) {
xhr.respond(200, 'number=1&space=one+two&empty=&encoded=a%2Bb&')
},
'/json': function(xhr) {
xhr.respond(200, JSON.stringify({name: 'Hubot', login: 'hubot'}))
},
Expand Down Expand Up @@ -80,6 +83,15 @@ asyncTest('resolves text promise', 1, function() {
})
})

asyncTest('parses form encoded response', 1, function() {
fetch('/form').then(function(response) {
return response.formData()
}).then(function(form) {
ok(form instanceof FormData, 'Parsed a FormData object')
start()
})
})

asyncTest('parses json response', 2, function() {
fetch('/json').then(function(response) {
return response.json()
Expand Down

0 comments on commit 60271ce

Please sign in to comment.