Angular controller structure - javascript

I'm a beginner with AngularsJs and I've got a question about the controller structure.
This is my employeeController.js
(function()
{
angular.module('employeeApp').controller('employeeController', employeeController);
function employeeController(employeeFactory,$routeParams,departmentFactory,schoolFactory,mentorFactory,constants,$location,$scope) {
var vm = this;
vm.employee = null;
vm.employees = null;
vm.profilePicture = null;
vm.mentors = null;
vm.schools = null;
vm.departments = null;
vm.roleId = constants.roleid;
vm.internEducators = null;
vm.overviewMentors = function() {
mentorFactory.overview(constants.companyid).then(function(response)
{
vm.mentors = response;
});
}
vm.create = function()
{
employeeFactory.create(vm.employee,vm.profilePicture).success(function(response,status)
{
if(status == 200)
{
$.toaster({message: 'De werknemer is toegevoegd'});
$location.path('/home');
}
}).error(function(response)
{
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function(error)
{
if(i <= 2)
{
$.toaster({ priority: 'danger', message: error});
}
i++;
});
});
}
vm.overviewInternEducators = function() {
employeeFactory.overviewInternEducators(constants.companyid).then(function(response)
{
vm.internEducators = response;
});
}
vm.overviewSchools = function() {
schoolFactory.overview(constants.companyid).then(function(response)
{
if(angular.isDefined(response[0].SchoolId))
{
vm.schools = response;
}
else
{
console.log('leeg!');
}
});
}
vm.overviewDepartments = function() {
console.log('test');
departmentFactory.overview(constants.companyid).then(function(response)
{
vm.departments = response;
});
}
vm.show = function() {
vm.isAdmin = employeeFactory.isAdmin();
employeeFactory.show($routeParams.id).then(function(response)
{
vm.employee = response;
});
}
vm.showDeleted = function() {
employeeFactory.showDeleted($routeParams.id).then(function(response)
{
vm.employee = response;
});
}
vm.update = function()
{
employeeFactory.update(vm.employee, vm.profilePicture).success(function(response, status)
{
if(status == 200)
{
vm.show(); // Zodat de nieuwe afbeelding wordt weergegeven
$.toaster({ message: 'De werknemer is geupdated' });
}
}).error(function(response)
{
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function(error)
{
if(i <= 2)
{
$.toaster({ priority: 'danger', message: error});
}
i++;
});
});
}
vm.overviewDeleted = function() {
employeeFactory.overviewDeleted().then(function(response)
{
if(angular.isDefined(response[0].EmployeeId))
{
vm.employees = response;
}
});
}
vm.delete = function() {
employeeFactory.delete($routeParams.id).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is verwijderd' });
$location.path('/home');
}
else
{
angular.forEach(response, function(error)
{
$.toaster({ priority: 'danger', message: error });
});
}
});
}
vm.permanentDelete = function(employeeId) {
employeeFactory.permanentDelete(employeeId).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is permanent verwijderd' });
$location.path('/prullenbak/werknemers');
}
else
{
angular.forEach(response, function(error)
{
$.toaster({ priority: 'danger', message: error });
});
}
});
}
vm.restore = function(employeeId) {
employeeFactory.restore(employeeId).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is teruggezet' });
$location.path('/werknemer/' + employeeId);
}
else
{
if(angular.isArray(response))
{
angular.forEach(response, function(error)
{
$.toaster({ priority : 'danger', message : error[0]});
});
}
}
});
}
<!--ng-init-->
vm.editEmployee = function()
{
vm.show();
vm.overviewDepartments();
vm.overviewInternEducators();
vm.overviewMentors();
vm.overviewSchools();
}
vm.createEmployee = function() {
vm.overviewMentors();
vm.overviewSchools();
vm.overviewDepartments();
vm.overviewInternEducators();
}
<!--redirects-->
vm.editRedirect = function(werknemerId)
{
$location.path('/werknemer/edit/' + werknemerId);
}
vm.showTrashedEmployeeRedirect = function(werknemerId)
{
$location.path('/prullenbak/werknemer/' + werknemerId);
}
}
})()
As you can see I use 2 methods called editEmployee and createEmployee (at the end). I use these 2 with the create employee page and the edit employee page. On both pages there are a couple of comboboxes that have to be loaded. In for example my create employee page I say ng-init="employeeController.createEmployee()" and then those comboboxes are filled.
I know this is not the best approach so how could I do this on a different and better way?

There are several ways to structure you app but the style guide endorsed by the Angular team is maintained by John Papa.
Refer to Angular Style Guide by John Papa.
Based on that:
First I would suggest that you split the create, show, edit and delete functionality into separate controllers. This helps with ensuring each controller does only one single thing.This is in line with the idea of Single Responsibility and Separation of Concerns
Secondly since it seems you are using the controllerAs syntax you wouldn't need to inject scope into your controller.
Here is the code for creating an employee(sth like create-employee.controller.js
(function () {
'use strict';
angular.module('employeeApp').controller('CreateEmployeeController', CreateEmployeeController);
//ngInject is used to help create minify safe version of the file during the build process.
//You should have this somewhere in your build process
/** #ngInject **/
function CreateEmployeeController(constants, departmentFactory, employeeFactory, $location, mentorFactory, schoolFactory) {
var vm = this;
vm.create = create;
getMentors();
getSchools();
getDepartments();
getInternEducators();
function getMentors() {
return mentorFactory.overview(constants.companyid).then(function (response) {
vm.mentors = response;
});
}
function getSchools() {
return schoolFactory.overview(constants.companyid).then(function (response) {
if (angular.isDefined(response[0].SchoolId)) {
vm.schools = response;
}
else {
console.log('leeg!');
}
});
}
function getDepartments() {
return departmentFactory.overview(constants.companyid).then(function (response) {
vm.departments = response;
});
}
function getInternEducators() {
return employeeFactory.overviewInternEducators(constants.companyid).then(function (response) {
vm.internEducators = response;
});
}
}
function create() {
return employeeFactory.create(vm.employee, vm.profilePicture).success(function (response, status) {
if (status == 200) {
$.toaster({message: 'De werknemer is toegevoegd'});
$location.path('/home');
}
}).error(function (response) {
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function (error) {
if (i <= 2) {
$.toaster({priority: 'danger', message: error});
}
i++;
});
});
}
})();
You would then create the other controllers by splitting the functionality following this example.

Related

Not getting response when register is successful

I have a Web API 2 register method as follows :-
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
and an angular Controller that posts to this api as follows :-
angular.module('monfusportsstoreApp')
.controller("registerCtrl", function($scope, UserService) {
var vm = this;
vm.register = register;
vm.Error = '';
function register() {
UserService.createUser(vm.user)
.then(function (response) {
console.log(response.data);
console.log(response.status);
if (response.success) {
console.log('Registration successful');
$location.path('/registerSuccess');
} else {
errorMessages = parseErrors(response);
for (var i = 0; i < errorMessages.length; i++) {
vm.Error += errorMessages[i];
}
}
});
}
function parseErrors(response) {
var errors = [];
for (var key in response.ModelState) {
for (var i = 0; i < response.ModelState[key].length; i++) {
errors.push(response.ModelState[key][i]);
}
}
return errors;
}
})
and the UserService is as follows :-
angular.module("monfusportsstoreApp")
.factory("UserService", function($http, ENDPOINT_URI){
var url = ENDPOINT_URI + '/api/Account/';
var errorMessage = [];
return {
getAllUsers: function() {
return $http.get(url).then(handleSuccess, handleError('Error getting all users'));
},
createUser: function(user) {
return $http.post(url + "/Register", user)
.then(handleSuccess, handleError);
}
}
function handleSuccess(res) {
return res.data;
}
function handleError(res) {
return res.data;
}
});
Now I am managing to trap the response error correctly and displaying the message, however when the Register API is successful and sends the OK, the response is always empty, and as so this piece of code
if (response.success) {
console.log('Registration successful');
$location.path('/registerSuccess');
is never triggered.
How can I trap the status 200 OK so that I can redirect the user to the RegisterSuccess page?
Thanks for your help and time!
I have solved this question.
In the UserService, I needed to return
function handleSuccess(res) {
return res.status;
}
so that in the controller, I can capture the response status
function register() {
UserService.createUser(vm.user)
.then(function (response) {
if (response == 200) {
console.log('Registration successful');
$location.path('/registerSuccess');
} else {
errorMessages = parseErrors(response);
for (var i = 0; i < errorMessages.length; i++) {
vm.Error += errorMessages[i];
}
}
});
}

Value of var goes back to empty after exiting function?

So I have an api request inside of a function thats placed in my Service script.. I have defined the variable "curruser" outside of the function so I can keep its value, however after exiting the follow Scirpt, curruser is empty??
services.js
function fbUserInfo() {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
So the console.log would return the proper JSON object I retrieved from facebook.. but when I return it in the return statement
return {
userInfo: function() {
fbUserInfo();
console.log(curruser);
return curruser;
}
it returns that curruser is an empty object! I did write
var curruser;
into the first line inside the ".factory"
you have to use then() since fbUserInfo() is async function
return {
userInfo: function() {
$.when(fbUserInfo())..then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
}).then(function(){
console.log(curruser);
return curruser;
})
}
Haven't tested this but might work.
var curruser;
function fbUserInfo( callback ) {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
callback(curruser);
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
return {
userInfo: function( callback ) {
fbUserInfo( function(data){
console.log(data);
callback(data);
});
}

Getting an Error in AngularJS Post 404 Bad Request Error

I am brand new to AngularJS and I'm pretty lost. On submitting a form I'm getting the error message: POST http://prerelease.vidaexpress.com/api/account/token 400 (Bad Request). The error happens when I try to submit the form. Maybe someone can help me. Part of my service is below:
(function () {
'use strict';
angular
.module('vidaexpress')
.service('accountService', accountService);
accountService.$inject = ['$http', '$window', '$rootScope', 'apiUrl'];
function accountService($http, $window, $rootScope, apiUrl) {
var baseUrl = apiUrl.account;
var cookieUser;
var sessionName = 'userInfo';
this.logIn = logIn;
this.logOut = logout;
this.signUp = signUp;
this.setUserInfo = setUserInfo;
this.getUserInfo = getUserInfo;
this.confirm = confirm;
this.recoveryPassword = recoveryPassword;
this.resetPassword = resetPassword;
this.sendVerifyEmail = sendVerifyEmail;
function logIn(credential) {
return $http({
method: 'POST',
url: baseUrl + 'token',
headers:{ 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
grant_type: 'password',
email: credential.email,
password: credential.password
}
}).then(function (response) {
if (!response) {
return { error: 'System Error' };
} else if (response.error) {
return { error: response.error };
} else {
return response.data;
}
}, function (error) {
return { error: 'System Error' };
});
}
function logout() {
return $http.post(baseUrl + 'logout');
}
function signUp(userInfo) {
return $http.post(baseUrl + 'signup', userInfo);
}
function setUserInfo(userInfo) {
cookieUser = userInfo;
$rootScope.currentUser = userInfo;
$window.sessionStorage.setItem(sessionName, JSON.stringify(userInfo));
}
function getUserInfo() {
if (!cookieUser) {
cookieUser = JSON.parse($window.sessionStorage.getItem(sessionName));
}
return cookieUser;
}
function confirm(customerId, token) {
$http.get(baseUrl + 'verifyEmail?id=' + customerId + '&token=' + token);
}
function recoveryPassword(email) {
return $http.get(baseUrl + 'recoveryPassword?email=' + email).then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
function resetPassword(model) {
return $http.post(baseUrl + 'resetPassword', model).then(function () {
return null;
}, function(){
return { error: 'System Error' };
});
}
function sendVerifyEmail() {
return $http.get(baseUrl + 'sendVerifyEmail').then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
}
})();
Here is my controller:
(function () {
'use strict';
angular
.module('vidaexpress')
.controller('accountController', accountController);
accountController.$inject = ['$rootScope', '$state', '$stateParams', 'accountService', 'facebookService', 'toastr'];
function accountController($rootScope, $state, $stateParams, accountService, facebookService, toastr) {
var vm = this;
vm.logIn = logIn;
vm.signUp = signUp;
vm.signOut = signOut;
vm.facebookLogin = facebookLogin;
vm.facebookLogout = facebookLogout;
vm.recoveryPassword = recoveryPassword;
vm.resetPassword = resetPassword;
vm.sendVerifyEmail = sendVerifyEmail;
function logIn(loginform) {
vm.signinloading = true;
accountService.logIn(loginform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
vm.login = {};
vm.submit = false;
accountService.setUserInfo(response);
if (!$rootScope.returncust) {
window.sessionStorage.setItem('returncust', true);
}
vm.isAccountOpen = false;
}
}, function (error) {
toastr.error(error.error);
}).finally(function () {
vm.signinloading = false;
});
}
function signUp(signupform) {
vm.signuploading = true;
accountService.signUp(signupform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.logIn(signupform).then(function (response) {
accountService.setUserInfo(response);
$state.go('main.index');
}, function(error) {
toastr.error(error.error);
});
}
},function (error) {
toastr.error('System Error');
}).finally(function () {
vm.signuploading = false;
});
}
function signOut() {
//Log out Facebook
var userInfo = accountService.getUserInfo();
if (userInfo.facebookLogin) {
facebookLogout();
}
//Log out UI
accountService.setUserInfo(null);
vm.isAccountOpen = false;
$state.go('main.index');
}
function facebookLogin() {
facebookService.login().then(function (response) {
if (response.status == 'connected' && $state.current.name == 'landing.index') {
$state.go('main.index');
} else {
vm.isAccountOpen = false;
}
});
}
function facebookLogout() {
facebookService.logout();
}
function recoveryPassword(email) {
accountService.recoveryPassword(email).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('An email has been sent.');
}
}, function () {
toastr.error('System Error');
});
}
function resetPassword(model) {
model.customerId = $stateParams.id;
model.token = $stateParams.token;
accountService.resetPassword(model).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Your password has been reset.');
}
}, function () {
toastr.error('System Error');
});
}
function sendVerifyEmail() {
accountService.sendVerifyEmail().then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Email has sent');
}
}, function () {
toastr.error('System Error');
});
}
}
})();
And here is my view:
<form class="form" name="loginform" ng-submit="loginform.$valid && vm.logIn(vm.login)" novalidate>
<div class="form-group">
<label for="email">{{'USERNAME' | translate}} ({{'EMAIL' | translate}})</label>
<input id="email" name="email" class="form-control" required ng-model="vm.login.email" ng-focus="vm.loginerror = '';" ng-pattern="/^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z0-9]{2,6}$/">
<div class="error_msg" ng-show="loginform.email.$error.required && vm.submit">{{ 'EMAIL_ENTER' | translate }}</div>
<div class="error_msg" ng-show="loginform.email.$error.pattern && vm.submit">{{ 'EMAIL_ERROR_PATTERN' | translate }}</div>
</div>
<div class="form-group">
<label for="password">{{'PASSWORD' | translate}}</label>
<input id="password" name="password" type="password" class="form-control" required ng-model="vm.login.password" ng-focus="vm.loginerror = '';">
<div class="error_msg" ng-show="loginform.password.$error.required && vm.submit">{{ 'PASSWORD_ENTER' | translate }}</div>
</div>
<div class="form-group">
<div class="error_msg">{{vm.loginerror}}</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary button_dkblue" ng-click="vm.submit=true;" ng-disabled="vm.signinloading" ve-btn-loading>{{'SIGN_IN' | translate}}</button>
</div>
<span><a ui-sref="password.recovery" ng-click="vm.isAccountOpen=false">{{ 'FORGOT_PASSWORD' | translate }}</a></span>
It's error from server side ,status code 404 means "NOT FOUND". The resources are not present which you are request for,so please check your token also it's correct or not
This is most likely coming from the URL you are posting to. Can you check the script you are sending this to? 404 isn't a javascript error, but where you are posting it to.

AngularJS Type Error

I am brand new to AngularJS and I'm debugging someone else's code. I am getting the following error when I debug in Google Chrome:
TypeError: accountService.logIn(...).success is not a function.
Here is some of my code. The problem is in the signUp form on the line accountService.logIn(signupform).success(function (response) {. If more info is needed please let me know.
Here is my entire controller.
(function () {
'use strict';
angular
.module('vidaexpress')
.controller('accountController', accountController);
accountController.$inject = ['$rootScope', '$state', '$stateParams', 'accountService', 'facebookService', 'toastr'];
function accountController($rootScope, $state, $stateParams, accountService, facebookService, toastr) {
var vm = this;
vm.logIn = logIn;
vm.signUp = signUp;
vm.signOut = signOut;
vm.facebookLogin = facebookLogin;
vm.facebookLogout = facebookLogout;
vm.recoveryPassword = recoveryPassword;
vm.resetPassword = resetPassword;
vm.sendVerifyEmail = sendVerifyEmail;
function logIn(loginform) {
vm.signinloading = true;
accountService.logIn(loginform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.setUserInfo(response);
if (!$rootScope.returncust) {
window.sessionStorage.setItem('returncust', true);
}
vm.isAccountOpen = false;
}
}, function (error) {
toastr.error(error.error);
}).finally(function () {
vm.signinloading = false;
});
}
function signUp(signupform) {
vm.signuploading = true;
accountService.signUp(signupform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.logIn(signupform).success(function (response) {
accountService.setUserInfo(response);
logIn();
}).error(function(error) {
toastr.error(error.error);
});
}
},function (error) {
toastr.error('System Error');
}).finally(function () {
vm.signuploading = false;
});
}
function signOut() {
//Log out API
//accountService.logOut();
//Log out Facebook
var userInfo = accountService.getUserInfo();
if (userInfo.facebookLogin) {
facebookLogout();
}
//Log out UI
accountService.setUserInfo(null);
vm.isAccountOpen = false;
$state.go('main.index');
}
function facebookLogin() {
facebookService.login();
}
function facebookLogout() {
facebookService.logout();
}
function recoveryPassword(email) {
accountService.recoveryPassword(email).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('An email has been sent.');
}
}, function () {
toastr.error('System Error');
});
}
function resetPassword(model) {
model.customerId = $stateParams.id;
model.token = $stateParams.token;
accountService.resetPassword(model).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Your password has been reset.');
}
}, function () {
toastr.error('System Error');
});
}
function sendVerifyEmail() {
accountService.sendVerifyEmail().then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Email has sent');
}
}, function () {
toastr.error('System Error');
});
}
}
})();
Here is my account.server.js file.
(function () {
'use strict';
angular
.module('vidaexpress')
.service('accountService', accountService);
accountService.$inject = ['$http', '$window', '$rootScope', 'apiUrl'];
function accountService($http, $window, $rootScope, apiUrl) {
var baseUrl = apiUrl.account;
var cookieUser;
var sessionName = 'userInfo';
this.logIn = logIn;
this.logOut = logout;
this.signUp = signUp;
this.setUserInfo = setUserInfo;
this.getUserInfo = getUserInfo;
this.confirm = confirm;
this.recoveryPassword = recoveryPassword;
this.resetPassword = resetPassword;
this.sendVerifyEmail = sendVerifyEmail;
function logIn(credential) {
return $http({
method: 'POST',
url: baseUrl + 'token',
headers:{ 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
grant_type: 'password',
email: credential.email,
password: credential.password
}
}).then(function (response) {
if (!response) {
return { error: 'System Error' };
} else if (response.error) {
return { error: response.error };
} else {
return response.data;
}
}, function (error) {
return { error: 'System Error' };
});
}
function logout() {
return $http.post(baseUrl + 'logout');
}
function signUp(userInfo) {
return $http.post(baseUrl + 'signup', userInfo);
}
function setUserInfo(userInfo) {
cookieUser = userInfo;
$rootScope.currentUser = userInfo;
$window.sessionStorage.setItem(sessionName, JSON.stringify(userInfo));
}
function getUserInfo() {
if (!cookieUser) {
cookieUser = JSON.parse($window.sessionStorage.getItem(sessionName));
}
return cookieUser;
}
function confirm(customerId, token) {
$http.get(baseUrl + 'verifyEmail?id=' + customerId + '&token=' + token);
}
function recoveryPassword(email) {
return $http.get(baseUrl + 'recoveryPassword?email=' + email).then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
function resetPassword(model) {
return $http.post(baseUrl + 'resetPassword', model).then(function () {
return null;
}, function(){
return { error: 'System Error' };
});
}
function sendVerifyEmail() {
return $http.get(baseUrl + 'sendVerifyEmail').then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
}
})();
The way your return pattern is working in the service requires your controller to use .then() rather than success()
accountService.logIn(loginform)
.then(function (response) {

How to use Promises/Chaining with Azure Mobile Services Custom API in Javascript

I am trying to figure out how to use Promises with the AMS Javascript API.
These are the two functions I have created that will be 'Promised'
function checkUsername(username, table) {
return table.where({username: username}).read({
success: function (results) {
if (results.length === 0) {
return true;
} else {
return false;
}
},
error: function(error) {
return false;
}
});
}
function checkEmail(email, table) {
return table.where({email: email}).read({
success: function (results) {
if (results.length === 0) {
return true;
} else {
return false;
}
},
error: function(error) {
return false;
}
});
}
checkUsername(body.username, accountsTable).then(function (results) {
if (results) {
return checkEmail(body.email, accountsTable);
} else {
response.send(400, {message: 'This username is already in use.'});
}
}).then(function(results) {
if (results) {
response.send(200, {message: 'Can proceed with sign up.'});
} else {
response.send(400, {message: 'This email address is already in use.'});
}
});
I am trying to use the promises as I would in Parse, but it's clearly not working. The console logs keep spitting out an Internal Server Error and that .then() is not a function of the object. I'm assuming I am missing a require or something in order to have the Promises functionality?
Error in script '/api/register.js'. TypeError: Cannot call method 'done' of undefined
at exports.post (D:\home\site\wwwroot\App_Data\config\scripts\api\register.js:30:59)
[external code]
I have realized what I was doing wrong.
I have now decided to use the Q Node Module for my promises.
var q = require('q');
exports.post = function(request, response) {
// Use "request.service" to access features of your mobile service, e.g.:
// var push = request.service.push;
var tables = request.service.tables;
var accountsTable = tables.getTable('Accounts');
var params = request.body;
checkUsername(params.username, accountsTable).then(function (result) {
if (result.length === 0) {
return checkEmail(params.email, accountsTable);
} else {
response.send(400, {message: 'This username is in use.'});
}
}).then(function (results) {
if (results.length === 0) {
return;
} else {
response.send(400, {message: 'This email address is already registered.'});
}
}).then(function () {
response.send(200, {message: 'Username and email are unique. You can register!'});
});
};
function checkUsername(username, table) {
var deferred = q.defer();
table.where({username: username}).read({
success: function (result) {
deferred.resolve(result);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}
function checkEmail(email, table) {
var deferred = q.defer();
table.where({email: email}).read({
success: function (result) {
deferred.resolve(result);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}

Categories

Resources