macchiato-framework / macchiato-core

Ring style HTTP server abstraction for Node.js
MIT License
377 stars 35 forks source link

Express Integration #5

Open njordhov opened 7 years ago

njordhov commented 7 years ago

I hacked Macchiato to work with the Express web framework, combining the two on the same server. It facilitates Express-based servers to be gradually converted to use Macchiato. And existing Express integrations such as Sente can immediately be used with Macchiato. This is the essential code:

(defn bidi-router [routes]                                                                                    
  (fn [req res]                                                                                                                  
    (if-let [route (some->> req :uri (bidi.bidi/match-route routes) :handler)]                                                   
      (route req res))))

(defn macchiato [http-router & [opts]]                                                                                           
  (let [route (macchiato.http/handler http-router opts)]                                                                         
    (fn [req res next]                                                                                                           
      (if-not (route req res)                                                                                                    
        (next)))))

Macchiato bidi routes can then be used with Express:

(doto (@express) 
    (.use "/" (macchiato (bidi-router routes))))

Perhaps it could be an optional module? I'd be glad to turn it into a PR.

yogthos commented 7 years ago

This is a great idea. Express has a large ecosystem around it, so it could fill a lot of the gaps immediately. Perhaps it could be wrapped up as a library. I can see it growing to provide cljs wrappers for the core Express API such as routing and middleware.

I'm thinking of using template profiles the way I do in Luminus, so you could have a +express profile that includes the library and sets up the plumbing for it when a new project is created.

theasp commented 6 years ago

@TerjeNorderhaug, I've added a Macchiato server adapter to use Sente directly: https://github.com/ptaoussanis/sente/pull/307

Example: https://github.com/theasp/sente-nodejs-example/tree/macchiato

yogthos commented 6 years ago

Thanks, mind if I add that under the official examples repo as well?

theasp commented 6 years ago

Sure, go right ahead, that's what it's for. :)

It might be a good idea to note that the example covers other frameworks too, just to avoid confusion.

yogthos commented 6 years ago

Perfect, and I'm thinking I'll factor out the macchiato specific stuff to make it simpler. I guess should probably wait until new sente pr is merged though.