koajs / joi-router

Configurable, input and output validated routing for koa
MIT License
450 stars 96 forks source link

Can't PUT or POST #27

Closed LouisLoode closed 8 years ago

LouisLoode commented 8 years ago

Hi, First, thanks for the awesome package, i just begin to use it. I make separation between routes, controllers and my handlers. All my GET routes of my crud works fine, but when i want to make validation on my POST and my PUT routes, it doesn't work. If i comment validate{}, in my route, it works. I think it's joi. But in the top of my file i have:

var router = require('koa-joi-router');
var Joi = router.Joi;

You can see a simple exemple of the skeleton of my API. The real project have a complete CRUD, if you want to see it, i can share the other pages. I separate my routes definitions in 3 parts, the route.js file :

var router = require('koa-joi-router');
// Controllers
var messageCntrl = require('./api/controllers/message');
module.exports = function(app) {
  var general = router();
  general.prefix('/api');
  general.route(messageCntrl.post);
// others routes
}

The controller:

var router = require('koa-joi-router');
var Joi = router.Joi;

// Handlers
var messageHndlr = require('../handlers/message');

var ctrl = module.exports = {};
// Need to fix
ctrl.post = {
  method: 'post',
  path: '/message',
   validate: {
     body: {
       name: Joi.string().max(100)
     },
     type: 'json',
   },
  handler: messageHndlr.post
};

The handler

var hdlr = module.exports = {};
hdlr.post = function *(next){
  yield next;
  var error, request, result;
  // console.log(this.request.body);
  console.log('dans le handler');
  try {
    var request = new Message(this.request.body);
    result = yield request.save();
    this.status = 200;
    return this.body = result;
  } catch (error) {
    // console.log(error);
    return boom.wrap(error, 400);
  }
};

You can see screen if you want but i don't have a lot of other informations: With validate in my controller (just loading long time and show this): with-validation

When i comment validate in my controller: without-validation

It doesn't works for body validate not for params, and i didn't test for headers. I expose POST route but it's exactly the same for my PUT route.

Thanks for your help

aheckmann commented 8 years ago

I take it "closed" means you figured it out? If not, I think the issue may be here:

} catch (error) {
    // console.log(error);
    return boom.wrap(error, 400);
}

The response is never written, leaving the request to hang.