vendredi 18 avril 2014

testing node.js using mocha and promises


Vote count:

0




I am building an API that uses CouchDB as a backend and whilst building the backend library I want to create a function in a library to add a user account and return success or failure but the callbacks are causing problems.


After reading up on JS Promises I realised that these would solve my problems but I can't get them to work despite reading lots of tutorials.


Could you take a look at my code and help me understand why it won't work?



var request = require('request');
var md5 = require('MD5');
var crypto = require('crypto');
var Q = require('q');

exports.new_account = function(params) {
console.log("\nNEW_ACCOUNT")
params.password = md5(params.password);
//console.log(params);
var token = crypto.randomBytes(16).toString('hex');
var record = {
type:"user",
status:"pending",
token:token,
credentials:params,
beacons_of_interest:{
count:0,
beacons:[]
}
};
console.log(record);

var uri = 'http://ift.tt/1jc3RR4'+params.email;
var deferred = Q.defer();
request({method: 'PUT', uri:uri, body: JSON.stringify(record)}, function (error, response, body) {
console.log('performing request')
var top = JSON.parse(body);
console.log(top);
if (top.error == 'conflict') {
console.log('the supplied email address already exists');
deferred.reject('account exists!');
}
console.log('resolving request')
deferred.resolve('account added.');
})
//var res = {status:"success", message:"Account created"};
return deferred.promise;
}


Thanks,



asked 23 secs ago






Aucun commentaire:

Enregistrer un commentaire