Skip to content

Commit 3016d6d

Browse files
authored
isInternalEntity: Assert the value is an object (#117)
* chore(utils): add "isObject" utility * fix(isInternalEntity): assert the value is object * fix(removeInternalProperties): remove unnecessary typeof check for internal entities
1 parent 808295f commit 3016d6d

4 files changed

Lines changed: 30 additions & 3 deletions

File tree

src/utils/isInternalEntity.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import { InternalEntity, InternalEntityProperty } from '../glossary'
2+
import { isObject } from './isObject'
23

34
/**
4-
* Determines if the given object is an internal entity.
5+
* Returns true if the given value is an internal entity object.
56
*/
67
export function isInternalEntity(
78
value: Record<string, any>,
89
): value is InternalEntity<any, any> {
910
return (
10-
value &&
11+
isObject(value) &&
1112
InternalEntityProperty.type in value &&
1213
InternalEntityProperty.primaryKey in value
1314
)

src/utils/isObject.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/**
2+
* Returns true if the given value is a plain Object.
3+
*/
4+
export function isObject(value: any): value is Record<string, any> {
5+
return value != null && typeof value === 'object' && !Array.isArray(value)
6+
}

src/utils/removeInternalProperties.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ function isOneOfRelation<
1313
>(
1414
value: Value<Dictionary[ModelName], Dictionary>,
1515
): value is InternalEntity<Dictionary, ModelName> {
16-
return typeof value === 'object' && isInternalEntity(value)
16+
return isInternalEntity(value)
1717
}
1818

1919
function isManyOfRelation(

test/utils/isObject.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { isObject } from '../../src/utils/isObject'
2+
3+
it('returns true given an empty object', () => {
4+
expect(isObject({})).toEqual(true)
5+
})
6+
7+
it('returns true given an object with values', () => {
8+
expect(isObject({ a: 1, b: ['foo'] })).toEqual(true)
9+
})
10+
11+
it('returns false given falsy values', () => {
12+
expect(isObject(undefined)).toEqual(false)
13+
expect(isObject(null)).toEqual(false)
14+
expect(isObject(false)).toEqual(false)
15+
})
16+
17+
it('returns false given an array', () => {
18+
expect(isObject([])).toEqual(false)
19+
expect(isObject([{ a: 1 }])).toEqual(false)
20+
})

0 commit comments

Comments
 (0)