Skip to content

Commit 2da9a3e

Browse files
fralonramcollina
authored andcommitted
Add json() handler for Response (#55)
* Add json() handler for Response * do not rethrow the error * Attach json parser to Response directly * Use indexOf to test header * Fix typo
1 parent 502878a commit 2da9a3e

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

lib/response.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,14 @@ function generatePayload (response) {
108108
res.body = res.payload
109109
res.trailers = response._lightMyRequest.trailers
110110

111+
// Prepare payload parsers
112+
res.json = function parseJsonPayload () {
113+
if (this.headers['content-type'].indexOf('application/json') < 0) {
114+
throw new Error('The content-type of the response is not application/json')
115+
}
116+
return JSON.parse(this.payload)
117+
}
118+
111119
return res
112120
}
113121

test/test.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -909,6 +909,58 @@ test('Should throw if both path and url are missing', (t) => {
909909
}
910910
})
911911

912+
test('Response.json() should parse the JSON payload', (t) => {
913+
t.plan(2)
914+
915+
const json = {
916+
a: 1,
917+
b: '2'
918+
}
919+
920+
const dispatch = function (req, res) {
921+
res.writeHead(200, { 'Content-Type': 'application/json' })
922+
res.end(JSON.stringify(json))
923+
}
924+
925+
inject(dispatch, { method: 'GET', path: 'http://example.com:8080/hello' }, (err, res) => {
926+
t.error(err)
927+
t.deepEqual(res.json(), json)
928+
})
929+
})
930+
931+
test('Response.json() should throw an error if content-type is not application/json', (t) => {
932+
t.plan(2)
933+
934+
const json = {
935+
a: 1,
936+
b: '2'
937+
}
938+
939+
const dispatch = function (req, res) {
940+
res.writeHead(200, { 'Content-Type': 'text/plain' })
941+
res.end(JSON.stringify(json))
942+
}
943+
944+
inject(dispatch, { method: 'GET', path: 'http://example.com:8080/hello' }, (err, res) => {
945+
t.error(err)
946+
t.throws(res.json, Error)
947+
})
948+
})
949+
950+
test('Response.json() should throw an error if the payload is not of valid JSON format', (t) => {
951+
t.plan(2)
952+
953+
const dispatch = function (req, res) {
954+
res.writeHead(200, { 'Content-Type': 'application/json' })
955+
res.end('notAJSON')
956+
}
957+
958+
inject(dispatch, { method: 'GET', path: 'http://example.com:8080/hello' }, (err, res) => {
959+
t.error(err)
960+
t.throws(res.json, Error)
961+
})
962+
})
963+
912964
function getTestStream (encoding) {
913965
const word = 'hi'
914966
let i = 0

0 commit comments

Comments
 (0)