Comments (18)
If it helps, I think tomorrow I can look into what changed in more recent versions that breaks custom responses.
from connect-api-mocker.
@koreem for lite-server specific implementation details, I need to check how is it working. Or maybe @raduserbanescu can help about that.
Also I created a task for writing tests for lite-server impl(#19) and another task for updating examples to have expressjs dependency-free examples(#20). Don't hesitate for creating PRs for them :)
from connect-api-mocker.
@raduserbanescu thanks for investigation the problem. Place for body-parser
is a big decision problem for me. Somehow I wanted to include it to make writing custom responses in an easy way but it effects so much problems. Also it makes testing upload endpoints harder. I think I need to think about that again.
Please, can you create a separate issue that defines that body-parser problem? Then we can continue to discuss in that issue for this specific problem and I think we can stop discussion here. Is it ok also for you? @koreem
from connect-api-mocker.
@muratcorlu
imho the following line in your non expressjs sample is wrong:
if (!fs.accessSync(targetFileName)) {
See https://nodejs.org/api/fs.html#fs_fs_accesssync_path_mode where it says that accessSync
returns undefined
on success and throw an Error
on error. Also I think targetFilename
is not the right parameter for accessSync
, it should be called with the filePath
.
Here's the sample I use:
var url = require('url');
var fs = require('fs');
var path = require('path');
module.exports = function (request, response) {
var targetFileName = 'GET.json';
var typeQueryParam = url.parse(request.url, true).query.type;
// Check is a type parameter exist
if (typeQueryParam) {
// Generate a new targetfilename with that type parameter
targetFileName = 'GET_' + typeQueryParam + '.json';
}
var filePath = path.join(__dirname, targetFileName);
// If file does not exist then respond with 404 header
try {
fs.accessSync(filePath);
}
catch (err) {
response.statusCode = 404;
response.end();
return;
}
var stat = fs.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': stat.size
});
var readStream = fs.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
}
from connect-api-mocker.
@muratcorlu: done #23
from connect-api-mocker.
Actually I never used lite-server. lite-server support was a contribution from @raduserbanescu. I just tried to test with lite-server and noticed that if I use index 1 for connect api mocker in middlewares, it just works but with 10, it doesn't work. But I don't know how that middleware definitions work in lite-server. Do you have any idea @raduserbanescu?
from connect-api-mocker.
When I use index 1 it almost works. I get a 'TypeError: Cannot read property 'type' of undefined' as mentioned in #13. Closed issue but without a solution? And thanks for that fast answer btw, appreciate it :)
from connect-api-mocker.
Do you have a custom response? If so, can you share the content of it?
from connect-api-mocker.
from connect-api-mocker.
Hi there all!
The reason to start the middleware from 10 is to not overwrite the default 2 provided by lite-server (or any other future ones that might be added).
I haven't had the chance to analyze your test case, but I see you are using a custom response inside a .js
file. I have noticed on some of my projects that the latest version has problems with this use case and I had to revert to an old version that I knew it worked (1.2.4
).
from connect-api-mocker.
I think we need some tests with lite-server. We shouldn't break that implementations.
For the custom responses, if lite-server doesn't use expressjs, that means request.query
will not work, because it's a feature of expressjs. otherwise request
object is nodejs http request object. then you will need to handle reading query parameters from that object. Can you just try an example custom response without request.query
?
from connect-api-mocker.
Maybe we should also update our examples without using expressjs like:
var url = require('url');
var fs = require('fs');
var path = require('path');
module.exports = function (request, response) {
var targetFileName = 'GET.json';
var typeQueryParam = url.parse(request.url, true).query.type;
// Check is a type parameter exist
if (typeQueryParam) {
// Generate a new targetfilename with that type parameter
targetFileName = 'GET_' + typeQueryParam + '.json';
// If file does not exist then respond with 404 header
if (!fs.accessSync(targetFileName)) {
response.statusCode = 404;
response.end();
return;
}
}
var filePath = path.join(__dirname, targetFileName);
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': stat.size
});
var readStream = fs.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
}
from connect-api-mocker.
Above example gives: ReferenceError: fileSystem is not defined
Example below gives: TypeError: request.get is not a function
Without custom reponses it works btw, so is there a working custom response example?
from connect-api-mocker.
@koreem I forgot to change a variable. Final result should be:
var url = require('url');
var fs = require('fs');
var path = require('path');
module.exports = function (request, response) {
var targetFileName = 'GET.json';
var typeQueryParam = url.parse(request.url, true).query.type;
// Check is a type parameter exist
if (typeQueryParam) {
// Generate a new targetfilename with that type parameter
targetFileName = 'GET_' + typeQueryParam + '.json';
// If file does not exist then respond with 404 header
if (!fs.accessSync(targetFileName)) {
response.statusCode = 404;
response.end();
return;
}
}
var filePath = path.join(__dirname, targetFileName);
var stat = fs.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': stat.size
});
var readStream = fs.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
}
For other example, all of the methods of request and response that we used(get
, status
, send
, sendFile
) come with expressjs. They are very good helpers but it's also possible to just write without these expressjs goodies.
from connect-api-mocker.
@muratcorlu Thanks, that example works. I still have to use id 1 for the middleware, but I don't think that's a problem.
from connect-api-mocker.
I did a little research and this is what I found:
1. @muratcorlu The reason my custom responses no longer work in the newest version is because of a breaking change in 1.3.5
, specifically in this commit.
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' events are no longer called in my code. Also 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?
2. @koreem lite-server
uses browser-sync
to create the server, which means you cannot use Express specific response properties in your custom responses as @muratcorlu pointed out.
Also, lite-server
is usually used as a development server for Single Page Applications built with Angular, React, etc. The first default middleware connect-history-api-fallback
is used to redirect requests to the index page so that the frontend application's router can handle it (see their docs for the conditions).
What I saw in your first error is that it is on the frontend side (so it should have nothing to do with lite-server
) and maybe it is caused by that redirection I spoke of previously (given the fact that when you overwrite it everything works).
from connect-api-mocker.
@khelkun thanks for sharing. I think you are right. I was already planning to update examples without using expressjs helpers. So maybe you can trigger this by creating a pull-request for this example :)
from connect-api-mocker.
I think we are done about this issue by adding separate specific issues/PRs as #23, #21, #20 and #19. So I'm closing this. If you think there are something more to discuss please feel free to reopen it.
from connect-api-mocker.
Related Issues (20)
- Undefined baseUrl property when using with Connect HOT 3
- Writing test cases for lite-server implementation
- Update(or add) express.js independent examples
- Custom response middleware without `body-parser` HOT 9
- put.js behaves slow(10s+) HOT 2
- Custom global response header for all requests.(CORS) HOT 1
- Catch all nested paths HOT 1
- Using semantic-release for automating releases HOT 1
- Returning images as mock HOT 6
- Custom response helper methods HOT 1
- Action required: Greenkeeper could not be activated 🚨
- Facing cors issue HOT 2
- [Feature Request] Add wildcard support for json files HOT 6
- [Feature Request] Enable logging HOT 4
- Mocking dosn't work when using absolut Urls HOT 1
- Parse FormData request HOT 1
- Can't seem to get anything from request.body with POST HOT 4
- Configuration with Next.js HOT 1
- generate JSON files HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from connect-api-mocker.