mswjs / http-middleware Goto Github PK
View Code? Open in Web Editor NEWSpawn 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
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
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)
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.
I tried to setup http-middleware
with graphql as both createServer
or createMiddleware
as the document, but it only works with rest
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.
Making POST request with JSON body, to mocked endpoint, produces body value as [object Object]
.
The cause of this lays on using express.json()
and then non-stringified JSON is changed to ArrayBuffer in createMiddleware
.
Parsing text to JSON:
Line 8 in ca84976
Encoding non-stringified JSON:
http-middleware/src/middleware.ts
Line 22 in ca84976
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.
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
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
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()
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.
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.
It seems that MockedRequest
is no longer exported from v2.0
We need a way to check compatibility with new msw release.
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!
Hi everyone , Is there any getting started guide to mock data for visual regression tests using mswjs/http-middleware?
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
.
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.
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 })
})
)
}
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!
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.
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.
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.
When using this library, I've noticed a behavior difference between createServer
and createMiddleware
. I think it's a bug in createMiddleware
.
Using identical handlers, the createServer implementation will provide a request.body
to the handler function, but createMiddleware will always return undefined
for request.body
.
There is a minimum-viable example gist here:
https://gist.github.com/nbibler/5f08424bc8411b87acc8e8f906dfdf5d
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.