문제

I'm using a expressjs 4.x to build a simple api on top of mongodb.

The api needs to serve a few sets of data:

/api/v1/datatype1 /api/v1/datatype2

For each data type, I have CRUD operations (post, get, put, delete).

The api requests would look like this:

POST /api/v1/datatype1
GET /api/v1/datatype1:_id 
PUT /api/v1/datatype1:_id 
DELETE /api/v1/datatype1:_id

If I create a router params like this:

dataType1ApiRouter.param("entity_id", function (req, res, next, id) {
   //async db fetch here by id, then call next with fetched data 
   //or error if faild request/not found entity.
   //let's say req.dataEntity = dataEtity; next();
} );

If I create a route like this:

 dataType1ApiRouter.route("/datatype1")
      .get(":entity_id", function (req, res, next) {
           //expcet req.dataEntity to be fetched by the param filter.
      })
      .post(function(req, res, next) {
          //just create an new dataType1 entity.
      });

I am getting a syntax error. The route .get and .post (and other methods like those) expect just one parameter, resulting in an error:

  Route.get() requires callback functions but got a [object String]

Is there a way to actually group all the "/datatype1" requests under one url declaration instead of repeating the method("datatype1:entity_id") for each method that requires the ID expect for the post method?

도움이 되었습니까?

해결책

There isn't a clean way to do this with Router.route(), but you might consider doing this with another Router instead of a Route there. Then, you could just mount that sub-router.

Basic example, modifying the code you provided:

var mainRouter = express.Router(),
    subrouter = express.Router();

subrouter.param("entity_id", function (req, res, next, id) {
    // param handler attached to subrouter
});


subrouter.post('/', function(req, res, next) {
    // post handler attached to base mount-point
});

subrouter.get("/:entity_id", function (req, res, next) {
    // get handler attached to base mount-point/<id>
});

// here we mount the sub-router at /datatype1 on the other router
mainRouter.use('/datatype1', subrouter);

Note that this requires adding a '/' to the URL, so instead of /api/v1/datatype1[someidhere] it would be /api/v1/datatype1/someidhere

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top