Skip to content

Commit

Permalink
feat: add paramsToFormData
Browse files Browse the repository at this point in the history
  • Loading branch information
luvletterldl committed Aug 25, 2022
1 parent 2530e05 commit 61ee926
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 13 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ console.log(urls) // ['http://a.g*o32^!.webp', 'https://%^&*.png']

### net
```ts
import { paramsToQuery } from '@fdutil/core'
import { paramsToQuery, paramsToFormData } from '@fdutil/core'

const params = {
a: 1,
Expand All @@ -69,6 +69,7 @@ const params = {
}
const url = '/example.com'
paramsToQuery(url, params) // '/example.com?a=1&b=2&c=3'
paramsToFormData(params) // to be FormData
```

### components
Expand Down
16 changes: 16 additions & 0 deletions packages/core/net/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,19 @@ export function paramsToQuery(url: string, params?: { [key: string]: any }) {
return url
}
}

/**
* params to FormData
* @param params params
* @returns FormData
*/
export function paramsToFormData(params: { [key: string]: any }) {
const formData = new FormData()
if (params && !isEmptyObject(params)) {
Object.keys(params).forEach((key) => {
if (params[key] !== undefined && params[key] !== null)
formData.append(key, params[key])
})
return formData
}
}
31 changes: 19 additions & 12 deletions test/core/net.test.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
import { describe, expect, test } from 'vitest'
import { paramsToQuery } from '../../packages/core/net'
import { paramsToFormData, paramsToQuery } from '../../packages/core/net'

describe('net moduel work!', () => {
const params = {
a: 1,
b: 2,
c: 3,
}
const specialParams = {
a: undefined,
b: null,
c: 1,
}
test('queryToQuery', () => {
const params = {
a: 1,
b: 2,
c: 3,
}
const specialParams = {
a: undefined,
b: null,
c: 1
}
const url = '/example.com'
const url1 = `${url}?`
const query = '?a=1&b=2&c=3'
expect(paramsToQuery(url, params)).toBe(url + query)
expect(paramsToQuery(url1, params)).toBe(url + query)
expect(paramsToQuery(url)).toBe(url)
expect(paramsToQuery(url, specialParams)).toBe(url + '?c=1')
expect(paramsToQuery(url, specialParams)).toBe(`${url}?c=1`)
})

test('queryToFormData', () => {
const fd = new FormData()
fd.append('c', '1')
expect(paramsToFormData(specialParams)?.get('c')).toBe('1')
expect(paramsToFormData(specialParams)?.get('b')).toBe(null)
})
})

0 comments on commit 61ee926

Please sign in to comment.