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

Parse query params for number primary keys in REST handlers

ruisaraiva19 opened this issue · comments

import { factory, primaryKey } from '@mswjs/data'

const db = factory({
  user: {
    id: primaryKey(Number), // Notice the primary key is of type Number
    firstName: String,
  },
})

db.user.toHandlers('rest')

db.user.create({
  id: 123,
  firstName: 'John',
})

// Will always return a 404 response
fetch('/users/123', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
  },
})

With the above example, when generating REST handlers, the following CRUD operations will not work as you would expect:

  • GET /users/:id (where "id" is your model's primary key), returns a user by ID;
  • PUT /users/:id, updates an existing user by ID;
  • DELETE /users/:id, deletes an existing user by ID;

These CRUD operations don't work because the where clause is using the request id params as a String, where on the database we have it as a Number. These values don't match when querying the database and because of that, it will always return a 404 response.

To fix this, some additional logic should be added to the generateRestHandlers function in order to detect if the primary key is of type Number and then cast the request id param value accordingly when passing it to the where clause.

FYI: I'm currently working on this!

A great find, @ruisaraiva19! Do you mind opening this in a standalone pull request? We can roll this bugfix out to the users in a faster manner then. Thanks!

@kettanaito yes, this will be a standalone pull request!

@kettanaito pull request is now ready for review.

Thank you, @ruisaraiva19! I'll try providing feedback today.

sounds good!