How to implement custom routes in sailsjs
I am trying to understand sails.js. First, I am trying to create a new api. This is my model and controller code
Coutries.js
module.exports = {
attributes: {
title:{
type:'string',
unique:true,
primaryKey:true
},
cities:{
collection:'Cities',
via:'country'
}
}
};
Cities, JS
module.exports = {
attributes: {
title: {
type:'string',
unique:true,
primaryKey:true
},
country:{
model:'Countries',
type:'String'
},
description: {
type:'string'
}
}
};
Further in routes.js I wrote
'get /countries':'CountriesController.getAllCountries'
I need a list of countries. I cannot figure out how to implement the getAllCountries function in CountriesController.js. I am using local db in tmp directory. Please, can anyone understand me in detail, how can I do this? Also tell me how to implement the addNewCountries function and updateCitiesDescription for example.
Thanks and sorry for my english)
source to share
Well, if your goal is just to browse the list of countries, then Sails will cover you. It provides a plan API that you can directly use to query your db and view the response as JSON.
For example, you can call
http://localhost:1337/countries
to view all countries in db. In a similar way, you can make other requests and also use the API directly. Find out more about it here
However, if you still want to query the database yourself to understand it, then what you have done so far is on the right track.
In your CountryController create a new action called "getAllCountries"
getAllCountries: function(req, res) {
Countries.find().exec(function(err, countries){
res.json(countries);
});
});
Your route basically tries to find a method called "getAllCountries" in the "CountryController" and redirects your request to that action.
After receiving the call, you simply fetch the list of countries from the database using the query language waterline and return the JSON to the user.
Friendly advice, avoid plural names of your models. For example, if you are trying to store countries and cities in your db, then name the models Country and City.
source to share
With sails, if you have a function to handle your routes, you create it internally api/controllers/CountriesController
as a method.
For routes:
'get /countries':'CountriesController.getAllCountries'
Country controller:
module.exports = {
getAllCountries: function (req, res, next){
return Country.getAllCountries(function success(countries){
//handle your success logic e.g: return res.view("countries", {data: countries});
}, function errorHandle(error){
//error handling
})
}
}
Country Model:
//inside your module.exports in api/models/Countries add this method
getAllCountries: function(cb, err){
Country.find({}).then(cb).catch(err);
}
To summarize, you use your controller method to communicate with the model and pass success and error handling functions that will return the appropriate view.
source to share