npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@illusionalsagacity/rescript-msw

v0.2.0

Published

ReScript bindings for MSW

Downloads

7

Readme

ReScript MSW

ReScript Bindings for msw v2. For msw versions <= 1, use version ~0.1.0 of this package.

[!WARNING] Breaking changes may happen on minor version releases in accordance with Semver.

Usage

let server = MSW.setupServer()
MSW.Server.listen(server)
...
MSW.Server.close(server)

graphql-ppx

This package provides a Functor for use with graphql-ppx under MSW.GraphQL.Response.Make to serve as a GraphQL response factory. It uses the modules returned by the %graphql extension point to serialize and deserialize operations; no more hand-writing verbose Js.Json chains with Js.Dict.fromArray->Js.Json.object_. Your request handler and responses are also typed to your operation module.

module UserQuery = %graphql(`
  query UserQuery($id: ID!) {
    userById(id: $id) {
      id
      avatarUrl
      fullName
    }
  }
`)

open MSW
let UserQueryHandler = GraphQL.Response.Make(UserQuery)
let handleSuccess = GraphQL.query(
  #Name("UserQuery"),
  ({request: _, variables, _}) => {
    UserQueryHandler.graphql(
      ~data={
        userById: Some({
          __typename: "foo",
          id: variables.id,
          avatarUrl: Some("http://test.com/avatar.png"),
          fullName: "John Doe",
        }),
      },
      { status: 200 },
    )
  })

let server = setupServer()
server->Server.listenWithOptions({onUnhandledRequest: #error})
server->Server.use(handleSuccess)

Note that you do not need to pass both the module and the name of the operation when using GraphQL_PPX.operation, only when using query or mutation.

More example usage can be found in the test which will also show you how to write your own tests using rescript-apollo-client.

GraphQL

If you are not using graphql-ppx, the standard MSW GraphQL handlers are available as zero-cost ReScript bindings under MSW.GraphQL.

module UserQuery = %graphql(`
  query UserQuery($id: ID!) {
    userById(id: $id) {
      id
      avatarUrl
      fullName
    }
  }
`)

open MSW
let server = setupServer()
server->Server.listenWithOptions({onUnhandledRequest: #error})
server->Server.use(
  GraphQL.query(
    #Name("UserQueryWithFragment"),
    async ({variables, _}) => {
      GraphQL.Response.graphql(
        ~data=Dict.fromArray([
          (
            "userById",
            Dict.fromArray([
              ("__typename", JSON.Encode.string("User")),
              (
                "id",
                variables
                ->Js.Dict.get("id")
                ->Option.mapOr(JSON.Encode.null, JSON.Encode.string),
              ),
              ("avatarUrl", JSON.Encode.string("http://test.com/avatar.png")),
              ("fullName", JSON.Encode.string("John Doe")),
            ])->JSON.Encode.object,
          ),
        ])->JSON.Encode.object,
        {
          status: 200,
          statusText: "OK",
        },
      )
    },
  )
)

Http

Zero-cost bindings are available for the Http handlers. Since there is no standard module type for the various ReScript JSON serialization libraries out there, these bindings will require you to encode and decode the responses yourself. An example using rescript-json-combinators can be found in __tests__/MSW__Http_test.res.

Alternative libraries: (in no particular order)

Additionally, the HttpResponse.jsonObj handler will accept objects for easier use in the case a serialization library is not being used:

open MSW
let server = setupServer()
server->Server.listenWithOptions({onUnhandledRequest: #error})
server->Server.use(
  Http.get(
    #URL("http://localhost/user/:id"),
    async ({request, params, cookies}) => {
      HttpResponse.jsonObj(
        {
          "id": "1",
          "avatarUrl": "http://test.com/avatar.png",
          "fullName": "John Doe"
        },
        {
          status: 200,
          statusText: "OK",
        },
      )
    },
  )
)

Motiviation

MSW is a fantastic utility library that has completely eclipsed my usage of @apollo/client's MockedProvider. In my opinion, it's a more "complete" test of your GraphQL operations, and it has been significantly less fussy in throwing spurious runtime errors or mysteriously not returning data during testing. My only complaint was that writing JSON encoders in ReScript was more effort than in TypeScript or JavaScript, and due to the way rescript-apollo-client + graphql-ppx parses GraphQL responses, writing tests in TypeScript for ReScript code while getting compiler errors is possible but tricky. Hence, these bindings.

Acknowledgements

Shout out to some older bindings to MSW by jichi here.