fix: filterByFields should return same value when input == null (close 0) (#41)

This commit is contained in:
Junyi 2020-12-13 17:12:44 +08:00 committed by GitHub
parent 5fd8139767
commit b6bce5a2dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 5 deletions

View File

@ -3,7 +3,7 @@ import { filterByFields } from '../utils';
describe('utils', () => { describe('utils', () => {
describe('filterByFields', () => { describe('filterByFields', () => {
it('only fields', async () => { it('only fields', () => {
const values = filterByFields({ const values = filterByFields({
title: 'title1', title: 'title1',
sort: 100, sort: 100,
@ -14,7 +14,7 @@ describe('utils', () => {
}); });
}); });
it('except fields', async () => { it('except fields', () => {
const values = filterByFields({ const values = filterByFields({
title: 'title1', title: 'title1',
sort: 100, sort: 100,
@ -28,7 +28,7 @@ describe('utils', () => {
}); });
}); });
it('only and except fields', async () => { it('only and except fields', () => {
const values = filterByFields({ const values = filterByFields({
title: 'title1', title: 'title1',
sort: 100, sort: 100,
@ -42,7 +42,7 @@ describe('utils', () => {
}); });
}); });
it('only and except fields with array', async () => { it('only and except fields with array', () => {
const values = filterByFields({ const values = filterByFields({
title: 'title1', title: 'title1',
comments: [ comments: [
@ -61,7 +61,7 @@ describe('utils', () => {
}); });
}); });
it('only and except fields with array', async () => { it('only and except fields with array', () => {
const values = filterByFields({ const values = filterByFields({
title: 'title1', title: 'title1',
user: { name: 'aaa', profile: { email: 'email' } }, user: { name: 'aaa', profile: { email: 'email' } },
@ -83,5 +83,26 @@ describe('utils', () => {
] ]
}); });
}); });
it('empty values', () => {
const values = filterByFields({}, {
only: ['a']
});
expect(values).toEqual({});
});
it('null values', () => {
const values = filterByFields(null, {
only: ['a']
});
expect(values).toBe(null);
});
it('undefined values', () => {
const values = filterByFields(undefined, {
only: ['a']
});
expect(values).toBeUndefined();
});
}); });
}); });

View File

@ -1,6 +1,10 @@
import _ from 'lodash'; import _ from 'lodash';
export function filterByFields(data: any, fields: any = {}): any { export function filterByFields(data: any, fields: any = {}): any {
if (data == null) {
return data;
}
const { const {
only = Array.isArray(fields) ? fields : null, only = Array.isArray(fields) ? fields : null,
except = [] except = []