Skip to content

Commit

Permalink
feat: add urlencoded method
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Feb 27, 2023
1 parent 5b81d17 commit 8474059
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
29 changes: 14 additions & 15 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,21 @@ const rawBody = async req => {

const rawBodyMap = new WeakMap()

const text = async req => {
const body = rawBodyMap.get(req)
if (body) return body
const buffer = await rawBody(req)
rawBodyMap.set(req, buffer)
return buffer.toString()
}

const buffer = async req => {
const body = rawBodyMap.get(req)
if (body) return body
const buffer = await rawBody(req)
rawBodyMap.set(req, buffer)
return buffer
let body = rawBodyMap.get(req)
if (body !== undefined) return body
body = await rawBody(req)
rawBodyMap.set(req, body)
return body
}

const json = (req, opts) => text(req, opts).then(JSON.parse)
const text = req => buffer(req).then(buffer => buffer.toString())

const json = req => text(req).then(JSON.parse)

const urlencoded = req =>
text(req).then(text =>
Object.fromEntries(new URLSearchParams(text).entries())
)

module.exports = { text, json, buffer }
module.exports = { text, json, buffer, urlencoded }
13 changes: 12 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ test('text', async t => {

test('json', async t => {
const url = await createServer(t, async (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
const json = await httpBody.json(req)
res.end(JSON.stringify(json))
})
Expand All @@ -61,3 +60,15 @@ test('buffer', async t => {
const { body } = await got.post(url, { body: Buffer.from('hello world') })
t.is(body, 'hello world')
})

test('urlencoded', async t => {
const url = await createServer(t, async (req, res) => {
res.end(JSON.stringify(await httpBody.urlencoded(req)))
})

const { body } = await got.post(url, {
form: new URLSearchParams([['foo', 'bar']])
})

t.is(body, JSON.stringify({ foo: 'bar' }))
})

0 comments on commit 8474059

Please sign in to comment.