Commit 0f15cfc9 authored by afc163's avatar afc163

Fix authority reading and add test case

parent 5bcf895a
import { isJsonString } from '@/utils/utils';
// use localStorage to store the authority info, which might be sent from server in actual project. // use localStorage to store the authority info, which might be sent from server in actual project.
export function getAuthority() { export function getAuthority(str) {
// return localStorage.getItem('antd-pro-authority') || ['admin', 'user']; // return localStorage.getItem('antd-pro-authority') || ['admin', 'user'];
const authorityString = localStorage.getItem('antd-pro-authority'); const authorityString =
typeof str === 'undefined' ? localStorage.getItem('antd-pro-authority') : str;
// authorityString could be admin, "admin", ["admin"]
let authority; let authority;
if (isJsonString(authorityString)) { try {
authority = JSON.parse(authorityString); authority = JSON.parse(authorityString);
} else { } catch (e) {
authority = [authorityString]; authority = authorityString;
}
if (typeof authority === 'string') {
return [authority];
} }
return authority || ['admin']; return authority || ['admin'];
} }
export function setAuthority(authority) { export function setAuthority(authority) {
let authorityString; const proAuthority = typeof authority === 'string' ? [authority] : authority;
if (isJsonString(authority)) { return localStorage.setItem('antd-pro-authority', JSON.stringify(proAuthority));
authorityString = JSON.stringify(authority);
} else {
authorityString = [authority];
}
return localStorage.setItem('antd-pro-authority', authorityString);
} }
import { getAuthority } from './authority';
describe('getAuthority should be strong', () => {
it('empty', () => {
expect(getAuthority(null)).toEqual(['admin']); // default value
});
it('string', () => {
expect(getAuthority('admin')).toEqual(['admin']);
});
it('array with double quotes', () => {
expect(getAuthority('"admin"')).toEqual(['admin']);
});
it('array with single item', () => {
expect(getAuthority('["admin"]')).toEqual(['admin']);
});
it('array with multiple items', () => {
expect(getAuthority('["admin", "guest"]')).toEqual(['admin', 'guest']);
});
});
...@@ -181,14 +181,3 @@ export function formatWan(val) { ...@@ -181,14 +181,3 @@ export function formatWan(val) {
export function isAntdPro() { export function isAntdPro() {
return window.location.hostname === 'preview.pro.ant.design'; return window.location.hostname === 'preview.pro.ant.design';
} }
export function isJsonString(str) {
try {
if (typeof JSON.parse(str) === 'object') {
return true;
}
} catch (e) {
return false;
}
return false;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment