mswjs / data

Data modeling and relation library for testing JavaScript applications.

Home Page:https://npm.im/@mswjs/data

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support modeling of non-queryable data

kettanaito opened this issue · comments

Motivation

Not all the modeled data are meant to be queryable. In certain cases, it's required to only describe the objects and have an API to seed them on demand. The required primaryKey at the moment prevents such usage of the library.

API

I suggest adding a new public API designed for modeling objects in general, without querying capabilities. The factory could then reuse this new API internally, appending querying support.

import { model } from '@mswjs/data'

const formData = model({
  username: String,
  password: faker.random.password,
})

formData.create()
formData.create({ username: 'john.maverick' })
formData.create({ username: 'joe', password: 'secret+123' })

Specification

  • The model function accepts a model dictionary—an object of properties and their default value getters. Much like the factory does now, with the exception of the required primaryKey and relationships.
  • The model function returns the following object:
interface Model {
  create(initialValues: Values): Entity
}
  • Calling model.create() returns a plain object with the described properties populated. There's no internal storage like Database for the factory.
  • Calling model.create() behaves like db.model.create() at the moment.
  • Model does no validation for entity uniqueness; multiple same entities can be created independently.
  • You cannot update/delete created entities via a designated API.

I was thinking about this the other day and thought it would be a great addition. In the Ruby world with factory_bot they had a method called build which allowed for creating non-persisted entities. https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#build-strategies