yonathan06 / fastify-now

File based routing for fastify https://github.com/fastify/fastify
MIT License
72 stars 8 forks source link

Does it allow to add routes dynamically? #2

Closed ialpert closed 4 years ago

ialpert commented 4 years ago

Hey, @yonathan06 !

First of all, impressive work, thanks for this plugin!

I do have a question -- does it allow to add routes/modules in run time? I'm looking for some way to "hot" extend server and researching two different approaches:

I think your plugin is close to option 1; please let me know

Thanks!

yonathan06 commented 4 years ago

@ialpert thanks!

first, the plugin can be called problematically with fastify.register so you can call it on some condition (code changed, etc..) with that said, not sure it won't throw errors, and it will most defiantly won't remove routes (didn't see an option to that in fastify docs). So you will have to terminate the process and rerun it.

for the first option you described, I don't think you should keep your server alive when the code is changed, and just add/remove routes. I guess that you take this approach from front-end development, but those are two different cases - front-end app are stateful, where backend services are stateless, so should be terminated and rerun on code change, even if it is in local development.

for the second approach, you need a server application that route between your two process, you can use nginx for that.

If you meant something else please elaborate

ialpert commented 4 years ago

Yeah, I think it summarizes it pretty well.

What I do (in express like middleware) today is:

let server // This got updated once I receive results from "server" Webpack

app.use((req, res, next) => {
  if (server) {
    server.default.app.handler(req, res)
  } else {
    next()
  }
})

so it's a catch-all handler that tries to use another express app to handle the request.

For Fastify it would be something using:

 instance.addHook('preHandler', async (req, reply) => {
  // Call updated code here 
 //  server.default.app.handler(req, res)
})

I was aiming for the following layout:

Served by app1 (Webpack middleware):

*Served by app2 ("/" route)**

Served by app2 (defined as routes)

So if I have 2 Fastly apps, I guess I can do something like

app1.register(app2).listen(443)

But only before I started it. I was also thinking about versioned routes, but that sounds a bit more complicated then I'm willing to go :)

yonathan06 commented 4 years ago

Still not sure that the right way to solve those problems is with running two servers, or dynamically change the routing (still think that nginx is a better suit for routing between two servers in your machine) What I can do is export registerRoutes function that is used in the plugin, and then you can add the route without calling fastify.register

yonathan06 commented 4 years ago

check this commit https://github.com/yonathan06/fastify-now/commit/670bcb76960f478d0d46c739a5ff44c4f1d679dd