Coder Social home page Coder Social logo

mswjs / http-middleware Goto Github PK

View Code? Open in Web Editor NEW
96.0 4.0 12.0 228 KB

Spawn an HTTP server from your request handlers or apply them to an existing server using a middleware.

Home Page: https://npm.im/@mswjs/http-middleware

TypeScript 92.33% JavaScript 7.67%
msw http server express request handler middleware

http-middleware's People

Contributors

christoph-fricke avatar devniel avatar idolize avatar kettanaito avatar pacop avatar robbtraister avatar ruisaraiva19 avatar stijnvanhulle avatar yshrsmz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

http-middleware's Issues

Typescript failing with `graphql` handlers

Hi there, am working on implementing with the recent msw2 updates and wanted to ask if this has been seen before:

import { HttpResponse, RequestHandler, graphql } from 'msw'
import { createServer } from '@mswjs/http-middleware'

export const handlers: RequestHandler[] = [
  graphql.query('ListPosts', () => {
    return HttpResponse.json({
      data: {
        // Convert all posts to an array
        // and return as the "posts" root-level property.
        posts: [{ test: true }],
      },
    })
  }),
]
const httpServer = createServer(...handlers)

console.log('server listening on 9090')
httpServer.listen(9090)

Image 2023-11-15 at 12 51 00 PM

I am seeing some failing types here where the createServer expects some type HttpHandler.

Ironically, everything works fine when I cast as any, just curious if this is expected or a bad pattern.

Graphql keeps pending

I tried to setup http-middleware with graphql as both createServer or createMiddleware as the document, but it only works with rest

  • graphql handlers is pending with createMiddleware (sometimes 404, I'm not sure) 🤔
  • 404 with createServer

I don't know if I'm missing something or it's an issue. Can I have an example with graphql?

Note: I used msw for my nextjs, but since I had /pages/[...slug].tsx, it had issue with graphql endpoint, so I have to find another solution, seems http-middleware is what I'm looking for.

Q. Is there any roadmap for OpenAPI3 documentation?

Thanks for mswjs team and stand-alone service on this http-middleware application. It's amazing and easy usage to make stub application.

On the other hand, if the mocked API has been build up with implementation about real app, there would be needed to documation like OAS3. This has been spawn stand alone express in this module, so like swagger-ui-express and swagger-jsdoc would be used on diffent way maybe.

So is there any roadmap for OAS3?

Thanks for sharing your opinion.
Hope you well.

Incompatible with msw v0.44.0

 ERROR  msw_1.parseIsomorphicRequest is not a function                                                                                                                                                                                                                                                                                                                           12:44:23

  at /Users/yshrsmz/repos/github.com/yshrsmz/webapp/node_modules/@mswjs/http-middleware/lib/middleware.js:20:37
  at Generator.next (<anonymous>)
  at /Users/yshrsmz/repos/github.com/yshrsmz/webapp/node_modules/@mswjs/http-middleware/lib/middleware.js:8:71
  at new Promise (<anonymous>)
  at __awaiter (/Users/yshrsmz/repos/yshrsmz/webapp//node_modules/@mswjs/http-middleware/lib/middleware.js:4:12)
  at /Users/yshrsmz/repos/github.com/yshrsmz/webapp/node_modules/@mswjs/http-middleware/lib/middleware.js:18:32
  at Layer.handle [as handle_request] (/Users/yshrsmz/repos/yshrsmz/webapp//node_modules/express/lib/router/layer.js:95:5)
  at trim_prefix (/Users/yshrsmz/repos/github.com/yshrsmz/webapp/node_modules/express/lib/router/index.js:328:13)
  at /Users/yshrsmz/repos/github.com/yshrsmz/webapp/node_modules/express/lib/router/index.js:286:9
  at Function.process_params (/Users/yshrsmz/repos/github.com/yshrsmz/webapp/node_modules/express/lib/router/index.js:346:12)

parseIsomorphicRequest was removed in msw v0.44.0

Doubts about using with mswjs/data

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

Incorrect content-length header with msw@^2.2.0 and unicode characters

Background

Last week, [email protected] was released. As part of this, mswjs/msw#1996 (feat: automatically set "Content-Length" on text/json responses) was included.

This now adds a Content-Length header to all responses, calculated from body.length.toString()

The issue

On upgradeing to [email protected], I've been having an issue where the generated content-length is incorrect and my response has been truncated when using special characters.

I believe this affects all responses with unicode characters and breaks this package with the latest version of msw when suing unicode characters.

Reproduction

Use msw@^2.2.0

Modify the example to the following:

  http.post<LoginBody, LoginResponse>('/test', async ({ request }) => {
    const user = await request.json()
    const { username } = user

    return HttpResponse.json({
      username,
      firstName: 'John',
      company: 'CompanyName™',
    })
  }),

Output:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

The Content-Length was incorrectly calculated as 2 short.

Server breaks by simply adding @mswjs/data due to strict-event-emitter mismatch

package.json

{
  "name": "msw-practice",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@mswjs/data": "^0.11.2",
    "@mswjs/http-middleware": "^0.7.0",
    "msw": "^1.0.1",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.9.5"
  }
}

server.ts

import { createServer } from "@mswjs/http-middleware";
import { rest } from "msw";

type Test = {
  hello: string;
};

const handlers = [
  rest.get("/user", (req, res, ctx) => {
    return res(ctx.json({ firstName: "John" }));
  }),
];

const httpServer = createServer(...handlers);

httpServer.listen(9090);
console.info("Server started");

ran with npx ts-node-dev server.ts throws an error

strict_event_emitter_1.Emitter is not a constructor
at Object. (/Users/l.../node_modules/@mswjs/http-middleware/lib/middleware.js:17:17)

if you yarn remove @mswjs/data it works fine. However, if you need to keep @mswjs/data you have to add yarn add strict-event-emitter@^0.4.0 and it will work.

Hopefully you all can figure this one out. I couldn't find an older version of strict-event-emitter laying around for it to fail. Not sure what the issue is.

Thanks!

Peer dependencies too strict?

This package has msw@^0.33.0 as peer dependency.
This means that you cannot use it in your project if you have a lower msw version as devDependency.

Doesn't it really work with a lower version of msw? I think you could make the peer deps less strict.
Test the application with the lowest MSW version possible and set that as peer dep, for example >=0.25.

CORS support

I was going to ask for CORS support in the createServer method, but then I did this instead using createMiddleware:

import { createMiddleware } from '@mswjs/http-middleware';
import express from 'express';
import cors from 'cors';
import { handlers } from './handlers';

const app = express();

app.use(cors());
app.use(express.json());
app.use(createMiddleware(...handlers));

app.listen(8082);

Opening purely so if someone searches for CORS they can see how to add it.

Or maybe you can put it in the docs.

Question: Can you modify the mocked handlers per request

Hi, before I start to use your library I was wondering if it supported the ability to change the underlying mocked handlers for each test.

E.g.

// some pseudo code

test('some happy path') {
page.goTo("/login"); // this should be mocked with default 200 response

}

test('some failure path') {

// override the response to simulate failure
  server.use(
    http.get('/login', () => {
      return new HttpResponse(null, { status: 500 })
    })
  )

}

Proxy unhandled requests to a third-party server

Hi!

I use standalone server mode since there is no express server(our API is PHP driven).

Is it possible passthrough all not mocked/handled routes to external/real api? Where to write the url, etc?

Thank you!

Doesn't work when used with "express.json" middleware

Hey y'all big fan of MSW!

I've been using MSW & http-middleware together to create a mock GraphQL API for a few months & I've recently run into an issue after updating to MSW v0.44.2 & http-middleware v0.5.0. I have a very similar setup to the custom server example in this repo & after updating all GQL operations now seem to pass through & return a 404 "Mock not found".

I've put together a small example that reproduces the issue I'm seeing.

GQL request hang with MSW 0.47.2

Hey y'all, running into an issue when updating to MSW 0.47.2 where my GQL request never resolve. I'm able to log from the handler function so the request seems to make it but it never responses. Here is an example repo with the issue recreated.

Update handlers

In msw you can do setupServer(...handlers) / setupWorker(...handlers) but also worker.use(...handler) to override existing handlers.

This package runs middleware in express and it looks like when you set the handlers with setupServer(...handlers), it is not possible to override them using something like server.use. Is that correct?

I have created an extension on top of @mswjs/http-middleware to set/change handlers on run time by calling a special PUT endpoint. It replaces the resolvers for the registered handlers, but the solution would be cleaner when it replaces the complete endpoints with a similar API as worker.use.

You can find the repo at fvanwijk/msw-http-dynamic-middleware.

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.