ethanresnick / json-api

Turn your node app into a JSON API server (http://jsonapi.org/)
GNU Lesser General Public License v3.0
268 stars 41 forks source link

Non Express/Connect middleware compliant #91

Closed sescobb27 closed 8 years ago

sescobb27 commented 8 years ago

Hi, I was wondering why did you use that kind of request handling approach instead of the old express way of handling incoming request and letting users use your lib as a express middleware?. I'm asking because we have an express API and we want to adopt JSON API and we found your library, it is awesome and thank you for it, but if we use it we are forced to use it in a non standard way and to change A LOT of code in our backend and that's not a choice.

Is there another way we can use it without that Front.apiRequest.?

ethanresnick commented 8 years ago

Hi. Thanks for your nice words about the library! I think you should be able to make it work for your use case relatively easily.

First, though, here's why it works the way it does. Basically, I wanted my library to be usable with server libraries beyond express (like koa, hapi, etc), which have different signatures for the functions they use to handle an incoming request and different formats of the request/response objects that they ask those functions to manipulate. I wanted to shield the main code in this library from all those framework-specific differences. Therefore, there's a concept of an "http strategy", which can be different for each framework. The HTTP strategy handles the incoming request in whatever format the framework provides and converts it to a neutral Request object that the rest of this library uses; then, when the library's done it hands back a framework-neutral Response object to the strategy, and the strategy converts that neutral response to a format useable by the particular server framework.

Now, the Front.apiRequest method that you alluded to is a method on the express http strategy, so it does conform to Express's standard (req, res, next) signature. That means that you can very easily use other middleware before it runs, like so:

app.get("/posts", checkAuthenticated, otherMiddlewareEtc, Front.apiRequest.bind(Front))

The only thing you can't do quite as easily is call other middleware after Front.apiRequest, because it sends the response as soon as it's done working. However, if you need to override that behavior, you should be able to subclass the ExpressStrategy relatively easily, then redefine sendResources in that class to fit your needs.

Does that help?

sescobb27 commented 8 years ago

yeah, that totally make sense, thank you so much for your time and your explanation :smile:.

ethanresnick commented 8 years ago

Great! If that works, I'm gonna give this a close :)