Skip to content
Luis Eduardo Brito edited this page Aug 29, 2013 · 5 revisions

Introduction

Are defined in /api/controllers/ as [name].js. Example: /api/controllers/user.js.

The route to the controller have to be defined in the API Routes config file, located at: /routes/api.js

File structure: /api/controllers/test.js

module.exports = {
	
	// route: /test
	index: function(req, res) {
		res.json({
			test: "ok"
		})
	},
	
	// route: /test/get
	get: function(req, res) {
		res.json({
			test: "ok"
		})
	},

}

Deadling with policies

You can restrict the access to some blocks of code using the API Policies.

For example, you can restrict the access for authenticated users using a policy that checks the cookie like this:

var response = require("../adapters/response");

module.exports = function(req, res, ok) {

	if(req.cookies.authenticated == "true") {

		ok();
	}

	else {
		response(res).json({

			result: "error",
			description: "you're not logged in"
		});
	}
}

And then, in the controller, you put the code block that you wnat to protect inside the policy(req, res).check() function. The req and res params are the same given in the controller function by the Router.

	policy(req, res).check(["authenticated"], function() { 

		var _user = model.find("user",  {

			_id: req.cookies.user_id

		}, function(r) {

			if(!r[0])
				throw new Error("Error selecting user")

			response(res).json({

				result: "success",
				data: {
					user: r[0]._sanitize(r[0])
				}
			});
	});
Clone this wiki locally