Skip to content

Commit

Permalink
feat(router): add support for nested controller before/after model hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanfoster committed Nov 6, 2017
1 parent 4469597 commit 92d27e7
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,14 @@ class Router {
if (actionHooks && actionHooks.after) {
handlers.push(actionHooks.after.bind(controller));
}
} else if (controller.beforeModel || controller.afterModel) {
if (controller.beforeModel) {
handlers.unshift(controller.beforeModel.bind(controller));
}

if (controller.afterModel) {
handlers.unshift(controller.afterModel.bind(controller));
}
}

return handlers;
Expand Down
10 changes: 10 additions & 0 deletions test/fixtures/controllers/comments/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,18 @@
import Controller from "../../../../src/controller";

export default class CreateComment extends Controller {
beforeModel(req, res, next) {
this.beforeModel.called = true;
next();
}

model(req, res, next) {
res.send(201);
next();
}

afterModel(req, res, next) {
this.afterModel.called = true;
next();
}
}
30 changes: 30 additions & 0 deletions test/router_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,36 @@ describe("Router", function () {
done();
});
});

it("binds a beforeModel hook", function (done) {
router.resource("comment");
client = supertest(app);
controller = registry.lookup("controller:comment.create");

client.post("/comments").send({
name: "foo"
}).end(function (err, res) {
if (err) { return done(err); }

expect(controller.beforeModel.called).to.be.true;
done();
});
});

it("binds an afterModel hook", function (done) {
router.resource("comment");
client = supertest(app);
controller = registry.lookup("controller:comment.create");

client.post("/comments").send({
name: "foo"
}).end(function (err, res) {
if (err) { return done(err); }

expect(controller.afterModel.called).to.be.true;
done();
});
});
});

describe("#route", function () {
Expand Down

0 comments on commit 92d27e7

Please sign in to comment.