Skip to content

Commit

Permalink
feat(utils): add getUrlPathname and getUrlQueryParams for router (#88)
Browse files Browse the repository at this point in the history
* feat(utils): add getUrlPathname and getUrlQueryParams for router

* feat(utils): update getUrlPathname and getUrlQueryParams use URLSearchParams

* fix(utils): update type/node to adjust URLSearchParams.entries

* fix(util): update router method name

* fix(utils): update createFullUrlPath to generateFullUrlPath
  • Loading branch information
LuckyFBB authored Sep 21, 2023
1 parent 800b807 commit 78b243d
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 38 deletions.
39 changes: 28 additions & 11 deletions docs/utils.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
`true`表示通过兼容性检测,`false`表示不通过兼容性检测

```js
Utils.browserCheck(); // boolean
Utils.browserCheck(); // boolean
```
## checkExist
检查属性是否存在
Expand Down Expand Up @@ -91,13 +91,13 @@ Utils.isEqual({name:'sichen'},{name:'sichen'}) // true
* @param {[type]} name [description]
* @param {[type]} url [description] 可选参数,默认当前域
*/
Utils.getParameterByName(); //boolean
Utils.getParameterByName(); //boolean
```

例如:
```js
Utils.getParameterByName('name','http://baidu.com?name='1'); // 1
Utils.getParameterByName('name'); // 1
Utils.getParameterByName('name','http://baidu.com?name='1'); // 1
Utils.getParameterByName('name'); // 1
```
## getBase64
获取图片的 Base64 格式
Expand All @@ -108,7 +108,7 @@ Utils.isEqual({name:'sichen'},{name:'sichen'}) // true
* @param {[type]} img [description]
* @param {Function} callback [description]
*/
Utils.getBase64(img,callback);
Utils.getBase64(img,callback);
```
## getCssText
样式对象转 css style 风格转字符串
Expand All @@ -118,7 +118,7 @@ Utils.isEqual({name:'sichen'},{name:'sichen'}) // true
* @param {Record<string, any>} [object={}]
* @returns String
*/
Utils.getCssText(object: Record<string, any> = {});
Utils.getCssText(object: Record<string, any> = {});
````
例如:
Expand Down Expand Up @@ -216,7 +216,7 @@ Utils.textOverflowExchange('my name is sichen', 10) // "my name is..."
* @param {[type]} num [description]
* @param {[type]} precision [description]
*/
Utils.percent(num: number, precision?: number);
Utils.percent(num: number, precision?: number);
````
例如:
Expand Down Expand Up @@ -327,7 +327,7 @@ Utils.removeEmpty({ a: 'test', b: undefined, c: { d: undefined } }) // { a: 'tes
## mergeDeep
将两个对象进行深拷贝合并,对象内的同名对象也进行一次深拷贝合并
将两个对象进行深拷贝合并,对象内的同名对象也进行一次深拷贝合并
如果 obj2 存在 _isMergeAtom 属性,则直接使用 obj2,不再与 obj1 合并
```js
Expand Down Expand Up @@ -358,7 +358,7 @@ downLoadData({
`true`表示格式为 utf-8,`false`表示格式为非 utf-8 格式
```js
Utils.isUtf8('test'); // boolean
Utils.isUtf8('test'); // boolean
```
## utf16to8
Expand All @@ -367,7 +367,7 @@ downLoadData({
返回值为 utf-8 格式的字符串
```js
Utils.utf16to8('test'); // string
Utils.utf16to8('test'); // string
```
## base64Encode
Expand All @@ -376,5 +376,22 @@ downLoadData({
返回值为 utf-8 格式的字符串
```js
Utils.base64Encode('test'); // string
Utils.base64Encode('test'); // string
```
## generateFullUrlPath
传入地址和 url 参数生成完整的 url 地址
```js
Utils.generateFullUrlPath('/test/getUrlPathname', { a: 1, b: 2 }); // /test/getUrlPathname?a=1&b=2
Utils.generateFullUrlPath('/test/getUrlPathname', { a: 1, b: undefined }); // /test/getUrlPathname?a=1&b=undefined
Utils.generateFullUrlPath('/test/getUrlPathname', { a: 1, b: null }); // /test/getUrlPathname?a=1&b=null
Utils.generateFullUrlPath('/test/getUrlPathname', { a: 1, b: '' }); // /test/getUrlPathname?a=1&b=
```
## getQueryParameters
根据传入的 search,返回对象
```js
Utils.getQueryParameters('?a=1&b=2'); // { a: '1', b: '2' }
Utils.getQueryParameters('?a=1&b=undefined'); // { a: '1', b: 'undefined' }
Utils.getQueryParameters('?a=1&b=null'); // { a: '1', b: 'null' }
```
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"@types/fs-extra": "^8.0.1",
"@types/gulp": "^4.0.6",
"@types/jest": "^24.0.24",
"@types/node": "^13.1.0",
"@types/node": "^17.0.21",
"chalk": "^3.0.0",
"commitizen": "^4.0.3",
"commitlint": "^8.2.0",
Expand Down
2 changes: 1 addition & 1 deletion src/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const cookie = {
value: string | number | object | boolean,
days?: number,
domainStr?: string,
path: string = '/'
path = '/'
) {
let expires = '';
if (days) {
Expand Down
21 changes: 20 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,26 @@ const utils = {
}
return decodeURIComponent(results[2].replace(/\+/g, ' '));
},

/**
*
* @param pathname 地址
* @param queryParams url参数
* @returns 两者生成的完整url地址
*/
generateFullUrlPath(pathname: string, queryParams = {}) {
const params = new URLSearchParams(queryParams);
const queryString = params.toString();
return pathname + (queryString ? `?${queryString}` : '');
},
/**
*
* @param search location.search
* @returns query 参数
*/
getQueryParameters(search: string) {
const searchParams = new URLSearchParams(search);
return Object.fromEntries(searchParams.entries());
},
/**
* 获取图片的Base64格式
* @param {[type]} img [description]
Expand Down
39 changes: 19 additions & 20 deletions test/cookie.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,55 +44,54 @@ Object.defineProperty(window.document, 'cookie', {
});

describe('test cookie utils', () => {

beforeEach(() => {
cookies = []
})
cookies = [];
});

test('should get cookie value with name', () => {
document.cookie = 'a=1; domain=; path=/';
expect(cookie.getCookie('a')).toBe('1');
expect(cookie.getCookie('a', 'a=2; c=3;')).toBe('2')
})
expect(cookie.getCookie('a', 'a=2; c=3;')).toBe('2');
});

test('should return all cookies object', () => {
document.cookie = 'a=1; domain=; path=/';
document.cookie = 'b=2; domain=; path=/';
expect(cookie.getAllCookies()).toEqual({ a: "1", b: "2" });
})
expect(cookie.getAllCookies()).toEqual({ a: '1', b: '2' });
});

test('should support set cookie', () => {
cookie.setCookie('a', '1');
expect(cookie.getCookie('a')).toBe('1')
expect(cookie.getCookie('a')).toBe('1');

const day = 3;
cookie.setCookie('b', '2', day, 'test');
const foundCookie = cookies.find(item => item.name === 'b' && item.domain === 'test')
const foundCookie = cookies.find((item) => item.name === 'b' && item.domain === 'test');
expect(foundCookie).not.toBeUndefined();

const expires = new Date(foundCookie!.expires as string).getTime();
const expiresNow = new Date(Date.now() + day * 24 * 60 * 60 * 1000).getTime()
expect(expires).toBeLessThan(expiresNow)
})
const expiresNow = new Date(Date.now() + day * 24 * 60 * 60 * 1000).getTime();
expect(expires).toBeLessThan(expiresNow);
});

test('should support delete cookie', () => {
cookie.setCookie('a', 1);
cookie.deleteCookie('a')
cookie.deleteCookie('a');
expect(cookie.getCookie('a')).toBeNull();

cookie.setCookie('b', 1, 3, 'test', '/test');
cookie.deleteCookie('b')
cookie.deleteCookie('b');
expect(cookie.getCookie('b')).not.toBeNull();
cookie.deleteCookie('b', 'test', '/test')
cookie.deleteCookie('b', 'test', '/test');
expect(cookie.getCookie('b')).toBeNull();
})
});

test('should suppport delete all cookies', () => {
cookie.setCookie('a', 1, 3, 'test', '/');
cookie.setCookie('b', 2, 3, 'test', '/');
cookie.deleteAllCookies('', '/')
cookie.deleteAllCookies('', '/');
expect(cookie.getAllCookies()).not.toEqual({});
cookie.deleteAllCookies('test', '/')
cookie.deleteAllCookies('test', '/');
expect(cookie.getAllCookies()).toEqual({});
})
})
});
});
35 changes: 35 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ const {
transformArray,
removeEmpty,
mergeDeep,
generateFullUrlPath,
getQueryParameters,
} = Utils;

describe('utils.convertBytes', () => {
Expand Down Expand Up @@ -280,4 +282,37 @@ describe('utils:', () => {
).toEqual({ a: 'cover', b: 456 });
});
});
describe('generateFullUrlPath test', () => {
expect(generateFullUrlPath('/test/getUrlPathname', { a: 1, b: 2 })).toEqual(
'/test/getUrlPathname?a=1&b=2'
);
expect(generateFullUrlPath('/test/getUrlPathname', { a: 1, b: undefined })).toEqual(
'/test/getUrlPathname?a=1&b=undefined'
);
expect(generateFullUrlPath('/test/getUrlPathname', { a: 1, b: null })).toEqual(
'/test/getUrlPathname?a=1&b=null'
);
expect(generateFullUrlPath('/test/getUrlPathname', { a: 1, b: '' })).toEqual(
'/test/getUrlPathname?a=1&b='
);
});
describe('getQueryParameters test', () => {
expect(
getQueryParameters(
'?metaType=1&tabsKey=&tableId=1&dataSourceType=1&name=t_dtinsight_test'
)
).toEqual({
dataSourceType: '1',
metaType: '1',
name: 't_dtinsight_test',
tableId: '1',
tabsKey: '',
});
expect(getQueryParameters('?a=1&b=2')).toEqual({ a: '1', b: '2' });
expect(getQueryParameters('?a=1&b=undefined')).toEqual({
a: '1',
b: 'undefined',
});
expect(getQueryParameters('?a=1&b=null')).toEqual({ a: '1', b: 'null' });
});
});
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1632,10 +1632,10 @@
resolved "https://registry.yarnpkg.com/@types/node/-/node-12.20.24.tgz#c37ac69cb2948afb4cef95f424fa0037971a9a5c"
integrity sha512-yxDeaQIAJlMav7fH5AQqPH1u8YIuhYJXYBzxaQ4PifsU0GDO38MSdmEDeRlIxrKbC6NbEaaEHDanWb+y30U8SQ==

"@types/node@^13.1.0":
version "13.13.52"
resolved "https://registry.yarnpkg.com/@types/node/-/node-13.13.52.tgz#03c13be70b9031baaed79481c0c0cfb0045e53f7"
integrity sha512-s3nugnZumCC//n4moGGe6tkNMyYEdaDBitVjwPxXmR5lnMG5dHePinH2EdxkG3Rh1ghFHHixAG4NJhpJW1rthQ==
"@types/node@^17.0.21":
version "17.0.45"
resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.45.tgz#2c0fafd78705e7a18b7906b5201a522719dc5190"
integrity sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==

"@types/normalize-package-data@^2.4.0":
version "2.4.1"
Expand Down

0 comments on commit 78b243d

Please sign in to comment.