Giter Site home page Giter Site logo

How to handle query params about msw HOT 7 CLOSED

mswjs avatar mswjs commented on April 28, 2024
How to handle query params

from msw.

Comments (7)

kentcdodds avatar kentcdodds commented on April 28, 2024 1

I tried the above suggestion and that didn't work for me. I don't have time to investigate why (will try later) but I thought I'd let you know.

from msw.

kentcdodds avatar kentcdodds commented on April 28, 2024 1

Yup, this works:

  rest.get(`${apiUrl}/books`, async (req, res, ctx) => {
    if (!req.query.has('query')) {
      return ctx.fetch(req)
    }
    const query = req.query.get('query')

    let matchingBooks
    if (query) {
      matchingBooks = matchSorter(allBooks, query, {
        keys: [
          'title',
          'author',
          'publisher',
          {threshold: matchSorter.rankings.CONTAINS, key: 'synopsis'},
        ],
      })
    } else {
      // return a random assortment of 10 books not already in the user's list
      matchingBooks = getBooksNotInUsersList(getUser(req).id).slice(0, 10)
    }

    return res(ctx.json({books: matchingBooks}))
  }),

Thanks!

from msw.

kentcdodds avatar kentcdodds commented on April 28, 2024

Oh, also, is there a way to make the :query param optional?

from msw.

kettanaito avatar kettanaito commented on April 28, 2024

Why is this project not using path-to-regexp?

Historically, when this project started to use [email protected] it required to have about this amount of abstraction to achieve what MSW needs:

https://github.com/open-draft/msw/blob/ebf2f0c37519db7a420c5ebf6ddbfcda52dcd24f/src/utils/matchPath.ts#L62-L107

With the latest version of path-to-regexp it may make sense to re-introduce it to the library, although I'd like to have some reasons to do so. I'm using a tiny in-house alternative called node-match-path, which may not catch all the use cases, but does what I need.

How to handle query params?

I wouldn't advise going with http://localhost:8989/api/book?query=:query as it makes query position in the URI sensitive. For example, what if you have the following query: ?a=2&query=:query. I'd still expect such URI to match, as it has the query URL query parameter in place, but it won't match the provided RegExp. Generally, I don't think this is a scenario to be handled using path parameters.

Instead, you should specify which URL you would like to mock (without query) and decide on the mocking within the response resolver, basing your logic around req.query:

import { composeMocks, rest } from 'msw'

composeMocks(
  rest.get('http://localhost:8989/api/book', (req, res, ctx) => {
    const { query } = req.query

    // In case there is no such query parameter return the original response
    if (!query) {
      return ctx.fetch(req)
    }

    return res(
      ctx.json({
        title: 'The Magician',
        author: 'Raymond E. Feist'
      })
    )
  })
)

At the moment MSW performs no URL query parsing, which I think we should add. Handling query parameters was on my mind for some time, but I never got the moment to do it. This may be the right moment.

Please, would the solution suggested above satisfy your usage scenario? If not, elaborate why, I'd like to make this into the library in a proper way.

from msw.

kentcdodds avatar kentcdodds commented on April 28, 2024

In case it's helpful, here's what I have tried:

  rest.get(`${apiUrl}/books`, async (req, res, ctx) => {
    console.log('here we go')
    if (!req.query.hasOwnProperty('query')) {
      return ctx.fetch(req)
    }
    const {query} = req.query

    let matchingBooks
    if (query) {
      matchingBooks = matchSorter(allBooks, query, {
        keys: [
          'title',
          'author',
          'publisher',
          {threshold: matchSorter.rankings.CONTAINS, key: 'synopsis'},
        ],
      })
    } else {
      // return a random assortment of 10 books not already in the user's list
      matchingBooks = getBooksNotInUsersList(getUser(req).id).slice(0, 10)
    }
    await sleep()

    return res(ctx.json({books: matchingBooks}))
  }),

from msw.

kettanaito avatar kettanaito commented on April 28, 2024

Yes, accessing req.query won't work at the moment, as it's not implemented. I'm tacking this in #76.

I've decided to parse the URL using new URL(req.url) and provide the req.query = parsedUrl.searchParams. Standard URLSearchParams interface is handy when getting the query parameters and I think it should be favored over keeping req.query as an object.

The usage of req.query would be as follows:

res.get('/api/books', (req, res, ctx) => {
  const bookId = req.query.get('id')

  return res(ctx.json({ bookId })
})

from msw.

kettanaito avatar kettanaito commented on April 28, 2024

Released req.query support in 0.10.0. Published the Query parameters documentation to showcase how to access query parameters in response resolvers.

Internally, I made query params and hash to be dropped when request URL are compared.

@kentcdodds, could you please try it? I hope it works well for your use case.

from msw.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.