mswjs / data

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

Could the DB return a copy of the data when executing the query #196

Closed Francis-Tao-jinjin closed 2 years ago

Francis-Tao-jinjin commented 2 years ago

Currently, when using getAll to query the data from the DB will return the reference of the data. If I delete or modify some of the fields in the return data, the actual data stored in the DB will also be modified.

kettanaito commented 2 years ago

Hey, @Francis-Tao-jinjin.

Every database operation (create, update, delete, etc.) returns the end result of that operation. For example, calling an update returns the next state of the matched entity.

Was there an issue you've experienced around this? If so, please provide a reproduction repository where I could take a look at it.

kettanaito commented 2 years ago

I think I've understood what your use case was.

const entities = db.user.getAll()

// Delete 1 user at index 0.
entities.slice(0, 1)

Did I get it right?

If that's the case then the solution is rather straightforward: do not modify the data returned from .getAll(). A general rule of thumb: do not modify the data you don't own.

This library exposes declarative interface to modify the database entities. You can create, update, and delete any entities you wish. How the library stores the entities internally must not be your concern, as you must never work with the internal structures directly (or, if you have to, work in a read-only mode).