Skip to content

Doubts about using with mswjs/data #23

Description

@mauroaccornero

Hello,

I'm trying to use mswjs/data with mswjs/http-middleware with this code:

db.js

import { faker } from '@faker-js/faker'
import { factory, primaryKey, oneOf } from '@mswjs/data'

faker.seed(123)

function createItem(db) {
    return db.book.create({
        author: db.author.create(),
    })
}

const db = factory({
    book: {
        id: primaryKey(() => faker.datatype.uuid()),
        title: faker.lorem.text,
        year: faker.date.past().getFullYear(),
        author: oneOf('author')
    },
    author: {
        id: primaryKey(() => faker.datatype.uuid()),
        name: faker.name.fullName,
    },
})

for(let k = 0; k < 100; k++){
    createItem(db)
}

export default db

server.js

import express from 'express'
import { createMiddleware } from '@mswjs/http-middleware'
import db from "./db.js";

const app = express()

app.use(express.json())

app.use(createMiddleware(...db.book.toHandlers('rest'), ...db.author.toHandlers('rest')))

app.use((_req, res) => {
    res.status(404).send({ error: 'Mock not found' })
})

app.listen(process.argv[2],() => {
    console.log(`Mock server started on port ${process.argv[2]}`)
})

I start the server with

node ./server.js 9090

almost everything works fine but when I try to create a new book with a POST to localhost:9090/books and a JSON payload like:

{
    "title": "asdasdas",
    "year": 2013,
    "author": {
        "id": "b463b8bb-76cf-46a9-b266-5ab5730b69ba",
        "name": "Ms. Bessie Daniel"
    }
}

I get a 500 status code with this message:

{"message":"Failed to resolve a \"ONE_OF\" relationship to \"author\" at \"book.author\" (id: \"861737c5-7ecd-40a8-be99-634b46bad09a\"): expected a referenced entity to be \"author\" but got {\"id\":\"b463b8bb-76cf-46a9-b266-5ab5730b69ba\",\"name\":\"Ms. Bessie Daniel\"}"}

I verified that the author was correct and if I try to create a book without the author, the book it's correctly saved.

I tried different payloads with Postman, but without luck.

I'm using

    "msw": "^0.47.4",
    "@mswjs/data": "^0.10.2",
    "@mswjs/http-middleware": "^0.5.2",

with node v16.14.0

probably I'm missing something, any suggestion it's welcome.

update: Looks like the error comes from msw/data https://github.com/mswjs/data/blob/main/src/relations/Relation.ts#L172

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions