Skip to content

Commit

Permalink
fix: replace form-urlencoded with native APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan committed Jan 18, 2023
1 parent 7c12205 commit d56750c
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 18 deletions.
6 changes: 0 additions & 6 deletions package-lock.json

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

1 change: 0 additions & 1 deletion package.json
Expand Up @@ -100,7 +100,6 @@
"debug": "^4.3.4",
"decompress-response": "^7.0.0",
"follow-redirects": "^1.15.2",
"form-urlencoded": "^6.1.0",
"into-stream": "^6.0.0",
"is-plain-object": "^5.0.0",
"is-retry-allowed": "^2.2.0",
Expand Down
45 changes: 36 additions & 9 deletions src/middleware/urlEncoded.ts
@@ -1,10 +1,35 @@
import encode from 'form-urlencoded'
import {isPlainObject} from 'is-plain-object'

const isBuffer = (obj: any) =>
!!obj.constructor &&
typeof obj.constructor.isBuffer === 'function' &&
obj.constructor.isBuffer(obj)
import {isBuffer} from '../util/isBuffer'

function encode(data: Record<string, string | Set<number | string>>): string {
const query = new URLSearchParams()

const nest = (name: string, _value: unknown) => {
const value = _value instanceof Set ? Array.from(_value) : _value
if (Array.isArray(value)) {
if (value.length) {
for (const index in value) {
nest(`${name}[${index}]`, value[index])
}
} else {
query.append(`${name}[]`, '')
}
} else if (typeof value === 'object' && value !== null) {
for (const [key, obj] of Object.entries(value)) {
nest(`${name}[${key}]`, obj)
}
} else {
query.append(name, value as string)
}
}

for (const [key, value] of Object.entries(data)) {
nest(key, value)
}

return query.toString()
}

/** @public */
export function urlEncoded(): any {
Expand All @@ -22,12 +47,14 @@ export function urlEncoded(): any {
return options
}

return Object.assign({}, options, {
return {
...options,
body: encode(options.body),
headers: Object.assign({}, options.headers, {
headers: {
...options.headers,
'Content-Type': 'application/x-www-form-urlencoded',
}),
})
},
}
},
}
}
1 change: 0 additions & 1 deletion test-deno/import_map.json
Expand Up @@ -2,7 +2,6 @@
"imports": {
"create-error-class": "https://esm.sh/create-error-class@^3.0.2",
"debug": "https://esm.sh/debug@^4.3.4",
"form-urlencoded": "https://esm.sh/form-urlencoded@^6.1.0",
"is-plain-object": "https://esm.sh/is-plain-object@^5.0.0",
"parse-headers": "https://esm.sh/parse-headers@^2.0.5"
}
Expand Down
3 changes: 2 additions & 1 deletion test/urlEncoded.test.ts
Expand Up @@ -55,7 +55,8 @@ describe('urlEncoded middleware', () => {
'obj[prop2][0]': 'elem',
str: 'val',
emoji: '😀',
set: '1,two',
'set[0]': '1',
'set[1]': 'two',
})
})

Expand Down

0 comments on commit d56750c

Please sign in to comment.