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

use pagination with toHandlers

ramyareye opened this issue · comments

Hello, thanks for great library.

I need to paginate my generated data with toHandlers.

this is my handler:
export const handlers = db.post.toHandlers('rest', 'https://my.backend/posts')

and this is my query:
fetch("https://my.backend/posts?take=5")

but it doesn't work! any idea?

Hey, @ramyareye. Thanks for reaching out.

Your usage of the data library is correct. I think what is missing is the actual API interception logic that would tell your app to resolve HTTP requests against your data entities.

The .toHandlers() API is designed to be used with MSW, which is an API mocking library developed by our team. This is a bare example of how to achieve your usage:

import { setupWorker } from 'msw'
import { db } from './your-db'

const worker = setupWorker(
  ...db.post.toHandler('rest', 'https://backend.api.com/posts')
)

worker.start()

MSW comes with a detailed tutorial on how to get started in both browser and Node.js. And, of course, you can reuse the same handlers that are derived from your data models across browser/Node.js seamlessly.

Did you have MSW in place to enable API mocking? If you do and your use case still doesn't function as expected, could you please create a reproduction repository for us to look at?

Thanks for quick response. Actually I'm playing to make a SWR example :D you can find code here (sry it's a bit messy now...)

steps to reproduce:

git checkout add-infinite-custom-mutation-example
cd examples/optimistic-ui && yarn && yarn dev

I setup msw based on Nextjs example on both server and browser, you can check mocks folder, everything is fine except I need pagination with toHandlers!

Also would be happy if you got any suggestion about structure and faking the data :)

It looks like there is an issue in the library and how it handles the absence of the skip property (or when it's set to 0). Although we do allow 0 as a value of the "skip" and "take" pagination URL query parameters:

const skip = rawSkip == null ? rawSkip : parseInt(rawSkip, 10)
const take = rawTake == null ? rawTake : parseInt(rawTake, 10)

We seem to be treating 0 as an absence of value later down the chain:

if (take && skip) {
options = Object.assign(options, { take, skip })
}
if (take && cursor) {
options = Object.assign(options, { take, cursor })
}

This means that pagination without both "skip" + "take" / "cursor" + "take" is not functioning as intended at the moment. The pagination with both query parameters set functions as expected on both server and client.

I'll provision a fix and release it.

thanks, real quick :) possible to have a release or date of the next one?