data

data

JavaScript应用测试的数据建模和关系模拟库

@mswjs/data是一个JavaScript应用测试库,提供数据建模和关系模拟功能。它允许开发者直观地创建数据模型、建立模型间关系,并通过类数据库方式查询数据。该库支持与REST和GraphQL API模拟集成,有助于简化原型设计和测试流程。

@mswjs/data数据建模API模拟JavaScript测试数据库模拟Github开源项目
<p align="center"> <img src="logo.svg" alt="Data library logo" width="124" /> </p> <h1 align="center"><code>@mswjs/data</code></h1> <p align="center">Data modeling and relation library for testing JavaScript applications.</p> <br />

Motivation

When testing API interactions you often need to mock data. Instead of keeping a hard-coded set of fixtures, this library provides you with must-have tools for data-driven API mocking:

  • An intuitive interface to model data;
  • The ability to create relationships between models;
  • The ability to query data in a manner similar to an actual database.

Getting started

Install

$ npm install @mswjs/data --save-dev # or $ yarn add @mswjs/data --dev

Describe data

With this library, you're modeling data using the factory function. That function accepts an object where each key represents a model name and the values are model definitions. A model definition is an object where the keys represent model properties and the values are value getters.

// src/mocks/db.js import { factory, primaryKey } from '@mswjs/data' export const db = factory({ // Create a "user" model, user: { // ...with these properties and value getters. id: primaryKey(() => 'abc-123'), firstName: () => 'John', lastName: () => 'Maverick', }, })

See the Recipes for more guidelines on data modeling.

Throughout this document native JavaScript constructors (i.e. String, Number) will be used as values getters for the models, as they both create a value and define its type. In practice, you may consider using value generators or tools like Faker for value getters.

Using the primary key

Each model must have a primary key. That is a root-level property representing the model's identity. Think of it as an "id" column for a particular table in a database.

Declare a primary key by using the primaryKey function:

import { factory, primaryKey } from '@mswjs/data' factory({ user: { id: primaryKey(String), }, })

In the example above, the id is the primary key for the user model. This means that whenever a user is created it must have the id property that equals a unique String. Any property can be marked as a primary key, it doesn't have to be named "id".

Just like regular model properties, the primary key accepts a getter function that you can use to generate its value when creating entities:

import { faker } from '@faker-js/faker' factory({ user: { id: primaryKey(faker.datatype.uuid), }, })

Each time a new user is created, its user.id property is seeded with the value returned from the datatype.uuid function call.

Once your data is modeled, you can use Model methods to interact with it (create/update/delete). Apart from serving as interactive, queryable fixtures, you can also integrate your data models into API mocks to supercharge your prototyping/testing workflow.

API

factory

The factory function is used to model a database. It accepts a model dictionary and returns an API to interact with the described models.

import { factory, primaryKey } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, age: Number, }, })

Learn more about the Model methods and how you can interact with the described models.

Each factory call encapsulates an in-memory database instance that holds the respective models. It's possible to create multiple database instances by calling factory multiple times. The entities and relationships, however, are not shared between different database instances.

primaryKey

Marks the property of a model as a primary key.

import { factory, primaryKey } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), }, }) // Create a new "user" with the primary key "id" equal to "user-1". db.user.create({ id: 'user-1' })

Primary key must be unique for each entity and is used as the identifier to query a particular entity.

nullable

Marks the current model property as nullable.

import { factory, primaryKey, nullable } from '@mswjs/data' factory({ user: { id: primaryKey(String) // "user.title" is a nullable property. title: nullable(String) } })

Learn more how to work with Nullable properties.

oneOf

Creates a *-to-one relationship with another model.

import { factory, primaryKey, oneOf } from '@mswjs/data' factory({ user: { id: primaryKey(String), role: oneOf('userGroup'), }, userGroup: { name: primaryKey(String), }, })

Learn more about Modeling relationships.

manyOf

Creates a *-to-many relationship with another model.

import { factory, primaryKey, manyOf } from '@mswjs/data' factory({ user: { id: primaryKey(String), publications: manyOf('post'), }, post: { id: primaryKey(String), title: String, }, })

Learn more about Modeling relationships.

drop

Deletes all entities in the given database instance.

import { factory, drop } from '@mswjs/data' const db = factory(...models) drop(db)

Model methods

Each model has the following methods:

create

Creates an entity for the model.

const user = db.user.create()

When called without arguments, .create() will populate the entity properties using the getter functions you've specified in the model definition.

You can also provide a partial initial values when creating an entity:

const user = db.user.create({ firstName: 'John', })

Note that all model properties are optional, including relational properties.

findFirst

Returns the first entity that satisfies the given query.

const user = db.user.findFirst({ where: { id: { equals: 'abc-123', }, }, })

findMany

Returns all the entities that satisfy the given query.

const users = db.user.findMany({ where: { followersCount: { gte: 1000, }, }, })

count

Returns the number of records for the given model.

db.user.create() db.user.create() db.user.count() // 2

Can accept an optional query argument to filter the records before counting them.

db.user.count({ where: { role: { equals: 'reader', }, }, })

getAll

Returns all the entities of the given model.

const allUsers = db.user.getAll()

update

Updates the first entity that matches the query.

const updatedUser = db.user.update({ // Query for the entity to modify. where: { id: { equals: 'abc-123', }, }, // Provide partial next data to be // merged with the existing properties. data: { // Specify the exact next value. firstName: 'John', // Alternatively, derive the next value from // the previous one and the unmodified entity. role: (prevRole, user) => reformatRole(prevRole), }, })

updateMany

Updates multiple entities that match the query.

const updatedUsers = db.user.updateMany({ // Query for the entity to modify. where: { id: { in: ['abc-123', 'def-456'], }, }, // Provide partial next data to be // merged with the existing properties. data: { firstName: (firstName) => firstName.toUpperCase(), }, })

delete

Deletes the entity that satisfies the given query.

const deletedUser = db.user.delete({ where: { followersCount: { equals: 0, }, }, })

deleteMany

Deletes multiple entities that match the query.

const deletedUsers = db.user.deleteMany({ where: { followersCount: { lt: 10, }, }, })

toHandlers

Generates request handlers for the given model to use with Mock Service Worker. All generated handlers are automatically connected to the respective model methods, enabling you to perform CRUD operations against your mocked database.

REST handlers

import { factory, primaryKey } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, }, }) // Generates REST API request handlers. db.user.toHandlers('rest')

GraphQL handlers

import { factory, primaryKey } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, }, }) // Generates GraphQL API request handlers. db.user.toHandlers('graphql')

Scoping handlers

The .toHandlers() method supports an optional second baseUrl argument to scope the generated handlers to a given endpoint:

db.user.toHandlers('rest', 'https://example.com') db.user.toHandlers('graphql', 'https://example.com/graphql')

Recipes

Nullable properties

By default, all model properties are non-nullable. You can use the nullable function to mark a property as nullable:

import { factory, primaryKey, nullable } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, // "user.age" is a nullable property. age: nullable(Number), }, }) db.user.create({ id: 'user-1', firstName: 'John', // Nullable properties can be explicit null as the initial value. age: null, }) db.user.update({ where: { id: { equals: 'user-1', }, }, data: { // Nullable properties can be updated to null. age: null, }, })

You can define Nullable relationships in the same manner.

When using Typescript, you can manually set the type of the property when it cannot be otherwise inferred from the seeding function, such as when you want a property to default to null:

import { factory, primaryKey, nullable } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), age: nullable<number>(() => null), }, })

Nested structures

You may use nested objects to design a complex structure of your model:

import { factory, primaryKey, nullable } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), address: { billing: { street: String, city: nullable(String), }, }, }, }) // You can then create and query your data // based on the nested properties. db.user.create({ id: 'user-1', address: { billing: { street: 'Baker st.', city: 'London', }, }, }) db.user.update({ where: { id: { equals: 'user-1', }, }, data: { address: { billing: { street: 'Sunwell ave.', city: null, }, }, }, })

Note that you cannot mark a nested property as the primary key.

You may also specify relationships nested deeply in your model:

factory({ user: { id: primaryKey(String), address: { billing: { country: oneOf('country'), }, }, }, country: { code: primaryKey(String), }, })

Learn more about Model relationships.

Model relationships

Relationship is a way for a model to reference another model.

One-to-One

import { factory, primaryKey, oneOf } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, }, post: { id: primaryKey(String), title: String, // The "post.author" references a "user" model. author: oneOf('user'), }, }) const user = db.user.create({ firstName: 'John' }) const post = db.post.create({ title: 'My journey', // Use a "user" entity as the actual value of this post's author. author: user, }) post.author.firstName // "John"

One-to-Many

import { factory, primaryKey, manyOf } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), // "user.posts" is a list of the "post" entities. posts: manyOf('post'), }, post: { id: primaryKey(String), title: String, }, }) const posts = [ db.post.create({ title: 'First' }), db.post.create({ title: 'Second' }), ] const user = db.user.create({ // Assign the list of existing posts to this user. posts, }) user.posts // [{ title: "First" }, { title: "Second" }]

Many-to-One

import { factory, primaryKey, oneOf } from '@mswjs/data' const db = factory({ country: { name: primaryKey(String), }, user: { id: primaryKey(String), country: oneOf('country'), }, car: { serialNumber: primaryKey(String), country: oneOf('country'), }, }) const usa = db.country.create({ name: 'The United States of America' }) // Create a "user" and a "car" with the same country. db.user.create({ country: usa }) db.car.create({ country: usa })

Unique relationships

Both oneOf and manyOf relationships may be marked as unique. A unique relationship is where a referenced entity cannot be assigned to another entity more than once.

In the example below we define the "user" and "invitation" models, and design their relationship so that one invitation cannot be assigned to multiple users.

import { factory, primaryKey, oneOf } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), invitation: oneOf('invitation', { unique: true }), }, invitation: { id: primaryKey(String), }, }) const invitation = db.invitation.create() const john = db.user.create({ invitation }) // Assigning the invitation already used by "john" // will throw an exception when creating this entity. const karl = db.user.create({ invitation })

Nullable relationships

Both oneOf and manyOf relationships may be passed to nullable to allow instantiating and updating that relation to null.

import { factory, primaryKey, oneOf, nullable } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), invitation: nullable(oneOf('invitation')), friends: nullable(manyOf('user')), }, invitation: { id: primaryKey(String), }, }) const invitation = db.invitation.create() // Nullable relationships are instantiated with null. const john = db.user.create({ invitation }) // john.friends === null const kate = db.user.create({ friends: [john] }) // kate.invitation === null db.user.updateMany({ where: { id: { in: [john.id, kate.id], }, }, data: { // Nullable relationships can be updated to null. invitation: null, friends: null, }, })

Querying data

This library supports querying of the seeded data similar to how one would query a SQL database. The data is queried based on its properties. A query you construct depends on the value type you are querying.

String operators

  • equals
  • notEquals
  • contains
  • notContains
  • in
  • notIn

Number operators

  • equals
  • notEquals
  • gt
  • gte
  • lt
  • lte
  • between
  • notBetween
  • in
  • notIn

Boolean operators

  • equals

编辑推荐精选

蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI助手AI工具AI写作工具AI辅助写作蛙蛙写作学术助手办公助手营销助手
Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

聊天机器人AI助手热门AI工具AI对话
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

热门AI工具AI办公办公工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

模型训练热门AI工具内容创作智能问答AI开发讯飞星火大模型多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

AI助手热门AI工具AI创作AI辅助写作讯飞绘文内容运营个性化文章多平台分发
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多