0

I am using @mswjs/data to generate a mock database and I have a property order which is a number between 0 and the length - 1 of all entries. I want to render the current index in that property. I was looking through the GitHub repo, Google and StackOverflow, but was not able to find that.

So how can I render the current index when mocking the entries?

It only matters on creation, afterwards the property will be mutated when the items move around.

Otherwise, instead of the current index, it can be also just a random number between 0 and the last index of the entry, but it has to be unique and not shared among other entries.

Mähnenwolf
  • 720
  • 10
  • 30
  • Can you please post some more context? What should the `order` property control? How does it relate to the "current index"? When creating entities, there's no order as no order matters. Order matters when listing entities (i.e. via `.findMany()`). – kettanaito Dec 25 '21 at 17:37
  • @kettanaito the order property is for the frontend to know what the order of the entities is, so they can list them in the correct order. Someone from somewhere else already gave me an answer on this, though. It's as simple as having a function that just counts up. – Mähnenwolf Dec 27 '21 at 07:52

2 Answers2

1

Consider using the sort option when querying the entities to sort the output on the front-end.

const db = factory({
  user: {
    id: primaryKey(Number)
  }
})

db.user.findMany({
  // Sort by the "id" property on the "user".
  sort: {
    id: 'asc'
  }
})

The sort criterion doesn't have to be the primary key, it can be any key. Yet since order seems to be a vital part of your model, I say it should be described in it (you can even use a designated property order, that'll also work.

While it does behave similarly to the default way entities are sorted when created, you're no longer bound to this internal implementation detail of the library, and instead, you explicitly define how the returned entities must be sorted on a per-operation basis.

kettanaito
  • 974
  • 5
  • 12
  • 1
    Thank you, I will use that when querying them. The order property is used so users can manually sort their list to their liking. – Mähnenwolf Dec 27 '21 at 13:51
0

The answer was simpler than I anticipated.

const countUp = (() => {
  let id = 0;
  return () => id++;
})();

And then in the factory

const myEntityFactory = () => {
  return {
    order: countUp,
  }
};

And it counts up when creating new entities.

Mähnenwolf
  • 720
  • 10
  • 30