florianholzapfel / express-restify-mongoose

Easily restify mongoose databases
https://florianholzapfel.github.io/express-restify-mongoose/
MIT License
640 stars 155 forks source link

Option "generateMethods" to generate endpoint with specific available methods only #385

Open pimvanderheijden opened 6 years ago

pimvanderheijden commented 6 years ago

We are relying heavily on express-restify-mongoose. Great module!

For some endpoints of our micro-services we need to exclude specific methods, like allow GET's but not PUT, DELETE etc.

Would be amazing to have an option like "generateMethods" in the restify.serve function. The option will then expect an array of methods to be generated, which by default will be something like:

[
    "delete"
    "deleteOne"
    "get"
    "getOne"
    "getCount"
    "getShallow"
        "patch"
        "put"
]

I'm planning on creating a PR soon. Are you open to accommodating this feature?

Zertz commented 6 years ago

Glad it's working for you! :)

I think preMiddleware should cover that use case,

preMiddleware: (req, res, next) => {
  if (["delete", "put"].includes(req.method.toLowerCase())) {
    return res.sendStatus(403)
  }

  next()
}
pimvanderheijden commented 6 years ago

Yes, we're doing something similar now:

_.each @mongoose.connection.models, (Model) =>
    name = Model.collection.name

    debug "Setting up rest endpoints for collection #{name}"

    resitfy.serve @app, Model,
        name:       name

        preCreate: (req, res, next) =>
            return req.res.status(400).json { message: "POST not available" }

        preUpdate: (req, res, next) =>
            return req.res.status(400).json { message: "PUT/PATCH not available" }

       preDelete: (req, res, next) =>
            return req.res.status(400).json { message: "DELETE not available" }

Doing this differently for specific models takes some more effort, and especially when doing it over and over again in different ways in different projects, it would be great setting it as an option. I think it's a common use case anyway.

Also, the problem for me is that the routes are created in Express. They are now only blocked inside the middleware pipeline. Instead of a 400 (or 404), I would really like to see for example the express "Cannot POST ..." error for routes that are non-existent.