I am trying to query the questions collection of a Mongo DB. I have structured my application similar how Joe Eames defined the MEAN stack in his Pluralsight course. I have a situation where I need to make multiple gets using different number of parameters. It seems that I am always defaulting to the server fuction, questions.getQuestionAll().
In general what I want to be able to do is perform a get with set of parameters dynamically determined at run time. With that in mind I have created 3 gets: 1. Get a single question by _id 2. Get questions based on the dynamically defined set of parameters (Not all will be defined each time. 3. Get all questions
HTML Menu item
In the call below Construct_id is associated with each question
//Construct-menu-right.jade
li
a(ui-sref="questions({construct_id:construct._id})") Questions
//app.js
angular.module('app',['ngResource', 'ui.router','xeditable', 'inputDropdown']);
// Can add the $logProvider before the $routeProvider to add debug capabilities
// app.config(function($logProvider, $stateProvider, $locationProvider, $urlRouterProvider ){
angular.module('app').config(function($logProvider, $stateProvider, $locationProvider, $urlRouterProvider ){
$logProvider.debugEnabled(true);
var routeRoleChecks = {
admin: {auth: function(flAuth){
return flAuth.authorizeCurrentUserForRoute('admin')
}},
user: {auth: function(flAuth){
return flAuth.authorizeAuthenticatedUserForRoute()
}}
};
$locationProvider.html5Mode({
enabled: true,
requireBase: false, //required to specify base of application in our HTML
rewriteLinks: true //Angular will rewrite URLs as necessary (add# to older browsers)
});
$stateProvider
.state('questions', {
url: '/questions:id',
views: {
'content-header': {
templateUrl: '/app/main/main-header',
controller: 'flMainCtrl',
caseInsensitivitieMatch: true
},
'content-banner': {
templateUrl: '/app/constructs/construct-banner',
controller: 'flConstructCrudCtrl',
caseInsensitivitieMatch: true
},
'content-main': {
templateUrl: '/app/questions/question-list',
controller: 'flQuestionListCtrl',
controllerAs: 'questions:id',
caseInsensitivitieMatch: true
},
'content-left': {
templateUrl: '/app/questions/question-menu-left',
controller: 'flQuestionListCtrl',
//controllerAs: 'questions:id',
caseInsensitivitieMatch: true
},
'content-right': {
templateUrl: '/app/questions/question-menu-right',
controller: 'flQuestionListCtrl',
//controllerAs: 'questions:id',
caseInsensitivitieMatch: true
},
'content-footer': {
templateUrl: '/app/main/main-footer',
controller: 'flMainCtrl',
caseInsensitivitieMatch: true
}
}
})
$urlRouterProvider.otherwise('home');
});
angular.module('app').run(function($rootScope, $location){
$rootScope.$on('$stateChangeError', function(evt, current, previous, rejection){
if (rejection === 'not authorized'){
$location.path('/');
}
});
});
app.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
//flQuestionlistCtrl.js
angular.module('app').controller('flQuestionListCtrl', function($scope,flCachedQuestions,flQuestionQueryParameterService, $state ) {
$scope.questions = flCachedQuestions.query();
$scope.sortOptions = [{value: "statement", text: "Sort by Statement"},
{value: "sequenceNo", text: "Sort by SequenceNo"},
{value: "componentType", text: "Sort by ComponentType"}]
$scope.sortOrder = $scope.sortOptions[0].value;
$scope.createNewQuestion = function(){
$state.go('questionCreate');
}
});
//flCachedQuestions
angular.module('app').factory('flCachedQuestions', function(flQuestion, flQuestionQueryParameterService) {
// temporarily turn off cache
var questionList= null;
return {
query: function() {
console.log("flCachedQuestion - query function - start");
var constructId = flQuestionQueryParameterService.getConstructId();
var ownerId = flQuestionQueryParameterService.getOwnerId() ;
var ownerGroupId = flQuestionQueryParameterService.getOwnerGroupId();
var componentType = flQuestionQueryParameterService.getComponentType();
console.log("flCachedQuestion - variables set");
console.log("constructId " + constructId );
console.log("ownerId " + ownerId );
console.log("ownerGroupId " + ownerGroupId );
console.log("componentType " + componentType );
if(!questionList || questionList == null) {
console.log("flCachedQuestion - before queryByParams function - if questionList is null or does not exits");
questionList = flQuestion.queryByParams(constructId,ownerId,ownerGroupId,componentType);
console.log("flCachedQuestion - after queryByParams function ");
}else
{
console.log("flCachedQuestion - query function - if questionList is not null and does exits");
console.log("questionList = " + questionList );
}
return questionList;
},
empty: function() {
console.log("flCachedQuestion - empty function - start");
questionList = null;
console.log("flCachedQuestion - empty function - after setting questionList to null");
return questionList;
}
}
})
//flQuestions.js
angular.module('app').factory('flQuestion',function($resource){
var QuestionResource = $resource('/api/questions/:id', {_id: "@id"}, {
queryById: { method: 'GET', params: {id: '@id'} , isArray: true },
queryByParams: { method: 'GET', params: { construct_id: String, owner_id: String,ownerGroup_id: String, componentType: String } , isArray: true },
queryAll: { method: 'GET', isArray: true },
create: { method: 'POST'},
update: { method: 'PUT' },
delete: { method: 'DELETE', params: {id: '@id'}}
});
return QuestionResource;
});
//Server – route.js
var questions = require('../controllers/questions'),
module.exports = function(app){
app.get('/api/questions/{:id}', questions.getQuestionById);
app.get('/api/questions/{:construct_id, :owner_id, :ownerGroup_id, :componentType }', questions.getQuestionSubset);
app.get('/api/questions/{:construct_id }', questions.getQuestionSubset);
app.get('/api/questions', questions.getQuestionAll);
app.post('/api/questions', questions.createQuestion);
app.put('/api/questions', questions.updateQuestion);
app.delete('/api/questions/:id', questions.deleteQuestion);
app.all('/api/*', function(req,res){
res.sendStatus(404);
});
app.get('*', function ( req, res) {
res.render('index', {
bootstrappedUser: req.user
});
});
}
//Server – questions
var Question = require('mongoose').model('Question');
exports.getQuestionById = function(req,res) {
console.log("questions - getQuestionById ");
console.log("req.params.id " + req.params.id );
console.log("req.params.constructId " + req.params.constructId );
Question.findOne({_id:req.params.id}).exec(function(err,question){
if (err){
console.log("questions - getQuestionById -Error - No Question Retrieved");
}else
{
console.log("questions - getQuestionById -No Error - Question Data Retrieved");
}
res.send(question);
})
};
exports.getQuestionSubset = function(req,res){
var questionParameter = req.body;
var constructId = questionParameter.construct_id;
console.log("questions - getQuestionSubset ");
console.log("constructId " + constructId );
console.log("req.params.constructId " + req.params.constructId );
console.log("req.params.ownerId " + req.params.ownerId );
console.log("req.params.ownerGroupId " + req.params.ownerGroupId );
console.log("req.params.componentType " + req.params.componentType );
Question.find({construct_id:req.params.constructId}).exec(function(err,collection){
if (err){
console.log("questions - getQuestionSubset -Error - No Question Retrieved");
}else
{
console.log("questions - getQuestionSubset -No Error - Question Data Retrieved");
}
res.send(collection);
})
};
exports.getQuestionAll = function(req,res){
console.log("questions - getQuestionAll ");
console.log("req.params.id " + req.params.id );
console.log("req.params.constructId " + req.params.constructId );
Question.find({}).exec(function(err,collection){
if (err){
console.log("questions - getQuestionAll -Error - No Question Retrieved");
}else
{
console.log("questions - getQuestionAll -No Error - Question Data Retrieved");
}
res.send(collection);
})
};