mswjs / data

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

Allows to define getters that depends of another properties #245

Open soullivaneuh opened 2 years ago

soullivaneuh commented 2 years ago

I have a modeling like this:

hosting: {
  id: primaryKey(idNumberIncr()),
  name: faker.internet.domainName,
  slug: faker.lorem.slug,
  server: oneOf('server'),
},

On the production API, the slug property has a generated value that depends to the name property.

However, I have no way to reproduce that with the fake data factory, as I don't have the information on the getter, so I have to generate a random one.

Ideally, the simplest implementation way would be this:

hosting: {
  id: primaryKey(idNumberIncr()),
  name: faker.internet.domainName,
  slug: (item) => item.name.whatEverStringTransformation(),
  server: oneOf('server'),
},

Or maybe a way to define a custom function to process the given data on each .create and .update call.

What do you think?

kettanaito commented 12 months ago

There is no way to do that in v1.

In v2, you can derive a value from another value by using a new derivative() API:

import { id, factory, derivative } from '@mswjs/data'

factory({
  user: {
    id: id(String),
    age: Number,
    isAdult: derivative(({ age }) => age >= 18),
  }
})