muratcorlu / connect-api-mocker Goto Github PK
View Code? Open in Web Editor NEWConnect middleware that creates mocks for REST APIs
License: Apache License 2.0
Connect middleware that creates mocks for REST APIs
License: Apache License 2.0
If user doesn't have a main mocks folder, checking for wildcard paths part gives an error.
Under agreement folder that is properly mapped with connect-api-mocker and webpack, I have one dynamic response, post and put...something like this:
__agreementId__
Everything works fine but for some reason mapping of the PUT.js
is too slow, it takes sometime more than 10s for server to respond...I am saying on purpose mapping
because I have added logs into a put function and they are not even hit for that 10s, so process before it is taking it too long, not sure why...
any ideas?
p.s. also I have tried to remove everything we have in put and directly return 204, still same behavior
To have a chance to define a mock that will catch all requests that starts with a path could be great.
For example, lets say we have 2 endpoints like below:
/api/users/3123123/messages/321
/api/users/4343/messages
/api/users/213
For now there is no chance to catch all these 3 endpoints with a single custom middleware. Maybe to have a mock definition in a path like below could be useful:
mocks/api/users/__user_id*__/ANY.js
Notice the star char in the wildcard name. That could mean, that wildcard will match all of this paths and nested paths.
Let's think about this...
Providing some helper functions for custom responses would be great, like:
const { jsonResponse } = require('connect-api-mocker/helpers');
module.exports = jsonResponse({success: true});
or
const { delay, jsonResponse } = require('connect-api-mocker/helpers');
module.exports = [delay(200), jsonResponse({success: true})];
A list of some helper functions could be:
delay(milliseconds)
equivalent to setTimeout(next, milliseconds);
jsonResponse(data)
equivalent to res).json(data)
;success()
equivalent to res.status(200
notFound()
equivalent to res.status(404)
created()
equivalent to res.status(201)
send()
equivalent to res.end()
At the and that could be possible and helpful:
const { delay, created, send } = require('connect-api-mocker/helpers');
module.exports = [delay(1000), created(), send()];
If we want to mock an endpoint like GET /products/312/images
we need to create a GET.json file in folder structure like products/312/images
. And we need to clone that files for other product ids like:
products/424/images
products/1/images
Possible feature to simplify that process, create a folder name like products/__product_id__/images
and for matching requests, respond with realated json file or passing that product_id parameter to defined middlewares like GET.js or POST.js etc.
🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨
To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.
Since we didn’t receive a CI status on the greenkeeper/initial
branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.
If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/
.
Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.
Is it possible to delay mock responses to simulate slow networks? I am using webpack:
devServer: {
overlay: {
warnings: true,
errors: true
},
before: (app) => {
app.use(apiMocker('/api', 'mocks/api'));
},
}
Facing cors issue. I am running a CRA on 3000 and mockapi on 8080 (with express.js) and getting cors issue.
Access to XMLHttpRequest at 'http://localhost:8080/api/orders/inspection/1021455197' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am also using a proxy option in my package.json
It should work all of url prefixes like /api
, api
, /api/
or api/
. Also it should work with all kind of path targets like mocks/api
, /mocks/api
, /mocks/api/
etc.
Now most of our custom response examples are express.js dependent. And some of our officially supported implementations(like lite-server) don't use express. So updating or adding some examples that will work within all type of servers will be great.
If you have multiple path mapping like that, it doesn't work properly for now:
apiMocker({
'/projects': {
target: 'mocks/api/projects',
nextOnNotFound: true
},
'/analytics': {
target: 'mocks/api/analytics',
nextOnNotFound: true
}
});
Workaround for that kind of need is creating multiple middlewares by calling apiMocker
multiple. For example(for webpack):
...
setup: function(app) {
app.use(apiMocker({
'/projects': {
target: 'mocks/api/projects',
nextOnNotFound: true
}
});
app.use(apiMocker({
'/analytics': {
target: 'mocks/api/analytics',
nextOnNotFound: true
}
});
}
...
For some use cases, we need to able to return image responses as mocks. Like GET.json
or GET.xml
, GET.jpeg
should be returned for an image request. There are some tricky parts for this:
auto
type that is checking request content-type header and falls-back to json. But for images we should check mock files for this path in any case for image mock files.So idea is:
GET /path
with accept type application/json
we should only check path/GET.json
Request method | Request path | Accept type | Mock file to be checked |
---|---|---|---|
GET | /path | application/json | path/GET.json |
GET | /path | application/xml | path/GET.xml |
GET | /path | image/* | path/GET.(jpeg|gif|png...) |
GET | /path | */* | path/GET.(json|xml|jpeg|gif|png...) |
* Custom middlewares should have priority in any case
** If there is no prefered accept type and if there is a json mock file, it should be prioritised
Hello,
it would be cool if the wildcard is passed into the json files to, so { id: __project_uuid__ }
will return the current uuid.
Maybe the wildcard needs some type of escaping, eg: $__project_uuid__$
This would reduce the usage of more complicated js files.
Let's use semantic-release to automate release process.
Is there a way to set CORS headers?
Hey @muratcorlu
It would be nice if you could turn on logging, displaying informations like the request's url and what happend with it (json file loaded/ forwarded because no mock was found etc)
Add some more debug logs with an optional parameter
We need to write some test cases for lite-server implementation to be sure we are not breaking that implementation.
Hi, I'm trying to setup mockers for my app using connect, but I get this error:
TypeError: Cannot read property 'replace' of undefined
at trimSlashes (/project/node_modules/connect-api-mocker/api-mocker.js:29:15)
at /project/node_modules/connect-api-mocker/api-mocker.js:85:15
at call (/project/node_modules/connect/index.js:239:7)
at next (/project/node_modules/connect/index.js:183:5)
at next (/project/node_modules/connect/index.js:161:14)
at SendStream.error (/project/node_modules/serve-static/index.js:121:7)
at SendStream.emit (events.js:159:13)
at SendStream.error (/project/node_modules/serve-static/node_modules/send/index.js:270:17)
at SendStream.onStatError (/project/node_modules/serve-static/node_modules/send/index.js:421:12)
at next (/project/node_modules/serve-static/node_modules/send/index.js:764:28)
at /project/node_modules/serve-static/node_modules/send/index.js:772:23
at FSReqWrap.oncomplete (fs.js:166:21)
Unless I'm doing something wrong, it seems that the problem is in missing baseUrl property. Which is an Express specific thing. And even with Express it's only set when router is used, so it's still might be undefined.
In my case with Connect request is an IncomingMessage object, which doesn't have such a property.
My setup:
var connect = require('connect');
var app = connect();
var serveStatic = require('serve-static');
app.use(serveStatic(__dirname+'/public', {'index': ['index.html']}));
app.use('/mocks', serveStatic(__dirname+'/app/mocks'));
var apiMocker = require('connect-api-mocker');
app.use('/api', apiMocker('/mocks/api'));
app.listen(3333);
As first discussed here, in version 1.3.5
there is a breaking change (commit) that affects custom response middleware.
body-parser
was added before the custom middleware, which means that the request is consumed before it can reach the custom code. This means that the 'data' and 'end' request events are no longer called in the custom code. See this issue for a better explanation.
Maybe revert to the old code (let the response unaltered) and add a config option to enable parsing the JSON body for you?
Server.js is as follows
app.use(
'/api',
apiMocker('api', {
target: 'api',
bodyParser: {
type: 'urlencoded',
options: { extended: true }
},
verbose: ({ req, filePath, fileType }) =>
console.log(
`Mocking endpoint ${req.originalUrl} using ${filePath}.${fileType}.`
)
})
)
POST.js is as follows
module.exports = function (request, response) {
console.log(request.body)
return response.sendFile('229110161010.json', { root: __dirname })
}
The log I get is is just and empty {}
How do I access the data in the body on my post calls?
Hello,
the mockign dosnt work when I try to use an absolute URL (www.example.com/api/)
I already set the urlRoot to www.example.com/api/.
Hello Murat.
Would you have some documentation or something like that, on how to configure it to be used with next.js
hi everyone, I hope I understand correctly, this library does not generate JSON files? correct?
I was starting to develop a library that would allow me to generate JSON files, does something like this already exist?
I am so lucky to have this library in my life.
:)
Api Mocker can handle simple xml file responses based on request accept header.
We need a simple condition here: https://github.com/muratcorlu/connect-api-mocker/blob/master/api-mocker.js#L104
Hi there,
is it possible to read and parse data from a request that are being sent as FormData
?
const formData = new FormData()
formData.append('param1', 'value1')
formData.append('param2', 'value2')
fetch('/api/mock-url', {
method: 'POST',
body: formData,
})
And then in api/mock-url/POST.js
module.exports = function (request, response) {
// ???
}
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.