mswjs / data

Data modeling and relation library for testing JavaScript applications.
https://npm.im/@mswjs/data
MIT License
829 stars 52 forks source link

Use "Symbol" for internal entity properties #135

Closed kettanaito closed 3 years ago

kettanaito commented 3 years ago

GitHub

Changes

Motivation

This change originates from #132, where a recursive relationship resulted in an infinite loop. Upon investigation, the loop originated from the removeInternalProperties function that stripped a given entity of its internal properties (those were stored as regular properties under reserved keys). That function eventually stumbled upon a relational property, read it, tried to clean it, then found the nested relation, then nested, etc (the relation is expected to be circular but the library must not hang on it).

Diving into the matter further, I’ve tried storing the internal properties in a different way. My first try was to use Object.defineProperties, which appends properties that are non-enumerable by default. This worked nicely until I realized that the properties appended that way are lost when you assign the object (entity) into another data structure:

const entity = { id: 'abc-123' }
Object.defineProperty(entity, 'primaryKey', {
  // Exclude this property from being listed
  // when the end-developer works with the public entity.
  enumerable: true,
  value: 'id'
})
// Non-enumerable properties can still be accessed
// by reference.
entity.primaryKey // "id"

const db = new Map()
db.set('abc-123', entity)

const retrieved = db.get('abc-123')
// While regular properties are preserved,
retrieved.id // "abc-123"

// The defined ones are lost.
retrieved.primaryKey // undefined

This corrupted each entity once it was stored in the Database. Using Object.defineProperties was not an option for this use case.

Afterward, I’ve recalled symbols and thought to give them a try. It turned out symbols are great for this particular case, because they are non-enumerable, but also persist with the object regardless of where it’s being stored. It was decided to use symbols for storing internal entity properties.

Consequences