Use native promise api in services

This commit is contained in:
Tankred Hase 2014-12-11 18:12:37 +01:00
parent 7bb69c76b6
commit cc886ad402
18 changed files with 56 additions and 74 deletions

View File

@ -21,7 +21,6 @@
"$", "$",
"inject", "inject",
"Promise", "Promise",
"qMock",
"resolves", "resolves",
"rejects", "rejects",
"self", "self",

View File

@ -3,13 +3,13 @@
var ngModule = angular.module('woServices'); var ngModule = angular.module('woServices');
// expose an instance with the static dbName 'app-config' to store configuration data // expose an instance with the static dbName 'app-config' to store configuration data
ngModule.factory('appConfigStore', function(appConfigLawnchair, $q) { ngModule.factory('appConfigStore', function(appConfigLawnchair) {
return new DeviceStorage(appConfigLawnchair, $q); return new DeviceStorage(appConfigLawnchair);
}); });
// expose a singleton instance of DeviceStorage called 'accountStore' to persist user data // expose a singleton instance of DeviceStorage called 'accountStore' to persist user data
ngModule.factory('accountStore', function(accountLawnchair, $q) { ngModule.factory('accountStore', function(accountLawnchair) {
return new DeviceStorage(accountLawnchair, $q); return new DeviceStorage(accountLawnchair);
}); });
module.exports = DeviceStorage; module.exports = DeviceStorage;
@ -21,9 +21,8 @@ module.exports = DeviceStorage;
/** /**
* High level storage api that handles all persistence of a user's data on the device. * High level storage api that handles all persistence of a user's data on the device.
*/ */
function DeviceStorage(lawnchairDAO, $q) { function DeviceStorage(lawnchairDAO) {
this._lawnchairDAO = lawnchairDAO; this._lawnchairDAO = lawnchairDAO;
this._q = $q;
} }
/** /**
@ -43,7 +42,7 @@ DeviceStorage.prototype.init = function(dbName) {
*/ */
DeviceStorage.prototype.storeList = function(list, type) { DeviceStorage.prototype.storeList = function(list, type) {
var self = this; var self = this;
return self._q(function(resolve) { return new Promise(function(resolve) {
var key, items = []; var key, items = [];
list = list || []; list = list || [];

View File

@ -8,9 +8,8 @@ module.exports = Invitation;
* The Invitation is a high level Data Access Object that access the invitation service REST endpoint. * The Invitation is a high level Data Access Object that access the invitation service REST endpoint.
* @param {Object} restDao The REST Data Access Object abstraction * @param {Object} restDao The REST Data Access Object abstraction
*/ */
function Invitation(invitationRestDao, $q) { function Invitation(invitationRestDao) {
this._restDao = invitationRestDao; this._restDao = invitationRestDao;
this._q = $q;
} }
// //
@ -25,7 +24,7 @@ function Invitation(invitationRestDao, $q) {
*/ */
Invitation.prototype.invite = function(options) { Invitation.prototype.invite = function(options) {
var self = this; var self = this;
return self._q(function(resolve) { return new Promise(function(resolve) {
if (typeof options !== 'object' || typeof options.recipient !== 'string' || typeof options.sender !== 'string') { if (typeof options !== 'object' || typeof options.recipient !== 'string' || typeof options.sender !== 'string') {
throw new Error('erroneous usage of api: incorrect parameters!'); throw new Error('erroneous usage of api: incorrect parameters!');
} }

View File

@ -8,9 +8,7 @@ module.exports = LawnchairDAO;
/** /**
* Handles generic caching of JSON objects in a lawnchair adapter * Handles generic caching of JSON objects in a lawnchair adapter
*/ */
function LawnchairDAO($q) { function LawnchairDAO() {}
this._q = $q;
}
/** /**
* Initialize the lawnchair database * Initialize the lawnchair database
@ -19,7 +17,7 @@ function LawnchairDAO($q) {
*/ */
LawnchairDAO.prototype.init = function(dbName) { LawnchairDAO.prototype.init = function(dbName) {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
if (!dbName) { if (!dbName) {
throw new Error('Lawnchair DB name must be specified!'); throw new Error('Lawnchair DB name must be specified!');
} }
@ -42,7 +40,7 @@ LawnchairDAO.prototype.init = function(dbName) {
*/ */
LawnchairDAO.prototype.persist = function(key, object) { LawnchairDAO.prototype.persist = function(key, object) {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
if (!key || !object) { if (!key || !object) {
throw new Error('Key and Object must be set!'); throw new Error('Key and Object must be set!');
} }
@ -67,7 +65,7 @@ LawnchairDAO.prototype.persist = function(key, object) {
*/ */
LawnchairDAO.prototype.batch = function(list) { LawnchairDAO.prototype.batch = function(list) {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
if (!(list instanceof Array)) { if (!(list instanceof Array)) {
throw new Error('Input must be of type Array!'); throw new Error('Input must be of type Array!');
} }
@ -88,7 +86,7 @@ LawnchairDAO.prototype.batch = function(list) {
*/ */
LawnchairDAO.prototype.read = function(key) { LawnchairDAO.prototype.read = function(key) {
var self = this; var self = this;
return self._q(function(resolve) { return new Promise(function(resolve) {
if (!key) { if (!key) {
throw new Error('Key must be specified!'); throw new Error('Key must be specified!');
} }
@ -112,7 +110,7 @@ LawnchairDAO.prototype.read = function(key) {
*/ */
LawnchairDAO.prototype.list = function(type, offset, num) { LawnchairDAO.prototype.list = function(type, offset, num) {
var self = this; var self = this;
return self._q(function(resolve) { return new Promise(function(resolve) {
var i, from, to, var i, from, to,
matchingKeys = [], matchingKeys = [],
intervalKeys = [], intervalKeys = [],
@ -171,7 +169,7 @@ LawnchairDAO.prototype.list = function(type, offset, num) {
*/ */
LawnchairDAO.prototype.remove = function(key) { LawnchairDAO.prototype.remove = function(key) {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
self._db.remove(key, function(err) { self._db.remove(key, function(err) {
if (err) { if (err) {
reject(err); reject(err);
@ -188,7 +186,7 @@ LawnchairDAO.prototype.remove = function(key) {
*/ */
LawnchairDAO.prototype.removeList = function(type) { LawnchairDAO.prototype.removeList = function(type) {
var self = this; var self = this;
return self._q(function(resolve) { return new Promise(function(resolve) {
var matchingKeys = [], var matchingKeys = [],
after; after;
@ -226,7 +224,7 @@ LawnchairDAO.prototype.removeList = function(type) {
*/ */
LawnchairDAO.prototype.clear = function() { LawnchairDAO.prototype.clear = function() {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
self._db.nuke(function(err) { self._db.nuke(function(err) {
if (err) { if (err) {
reject(err); reject(err);

View File

@ -4,15 +4,13 @@ var ngModule = angular.module('woServices');
ngModule.service('newsletter', Newsletter); ngModule.service('newsletter', Newsletter);
module.exports = Newsletter; module.exports = Newsletter;
function Newsletter($q) { function Newsletter() {}
this._q = $q;
}
/** /**
* Sign up to the whiteout newsletter * Sign up to the whiteout newsletter
*/ */
Newsletter.prototype.signup = function(emailAddress, agree) { Newsletter.prototype.signup = function(emailAddress, agree) {
return this._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
// validate email address // validate email address
if (emailAddress.indexOf('@') < 0) { if (emailAddress.indexOf('@') < 0) {
reject(new Error('Invalid email address!')); reject(new Error('Invalid email address!'));

View File

@ -4,8 +4,7 @@ var ngModule = angular.module('woServices');
ngModule.service('oauth', OAuth); ngModule.service('oauth', OAuth);
module.exports = OAuth; module.exports = OAuth;
function OAuth($q, oauthRestDao) { function OAuth(oauthRestDao) {
this._q = $q;
this._googleApi = oauthRestDao; this._googleApi = oauthRestDao;
} }
@ -22,7 +21,7 @@ OAuth.prototype.isSupported = function() {
* @param {String} emailAddress The user's email address (optional) * @param {String} emailAddress The user's email address (optional)
*/ */
OAuth.prototype.getOAuthToken = function(emailAddress) { OAuth.prototype.getOAuthToken = function(emailAddress) {
return this._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
var idOptions = { var idOptions = {
interactive: true interactive: true
}; };
@ -59,7 +58,7 @@ OAuth.prototype.getOAuthToken = function(emailAddress) {
*/ */
OAuth.prototype.refreshToken = function(options) { OAuth.prototype.refreshToken = function(options) {
var self = this; var self = this;
return self._q(function(resolve) { return new Promise(function(resolve) {
if (!options.oldToken) { if (!options.oldToken) {
throw new Error('oldToken option not set!'); throw new Error('oldToken option not set!');
} }
@ -80,7 +79,7 @@ OAuth.prototype.refreshToken = function(options) {
*/ */
OAuth.prototype.queryEmailAddress = function(token) { OAuth.prototype.queryEmailAddress = function(token) {
var self = this; var self = this;
return self._q(function(resolve) { return new Promise(function(resolve) {
if (!token) { if (!token) {
throw new Error('Invalid OAuth token!'); throw new Error('Invalid OAuth token!');
} }

View File

@ -39,9 +39,7 @@ ngModule.factory('oauthRestDao', function() {
module.exports = RestDAO; module.exports = RestDAO;
function RestDAO($q) { function RestDAO() {}
this._q = $q;
}
/** /**
* Set the REST DAO's base url * Set the REST DAO's base url
@ -99,7 +97,7 @@ RestDAO.prototype.remove = function(uri) {
RestDAO.prototype._processRequest = function(options) { RestDAO.prototype._processRequest = function(options) {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
var xhr, format; var xhr, format;
if (typeof options.uri === 'undefined') { if (typeof options.uri === 'undefined') {

View File

@ -15,8 +15,7 @@ var TCPSocket = require('tcp-socket'),
* *
* @constructor * @constructor
*/ */
function ConnectionDoctor($q, appConfig) { function ConnectionDoctor(appConfig) {
this._q = $q;
this._appConfig = appConfig; this._appConfig = appConfig;
this._workerPath = appConfig.config.workerPath + '/tcp-socket-tls-worker.min.js'; this._workerPath = appConfig.config.workerPath + '/tcp-socket-tls-worker.min.js';
} }
@ -86,7 +85,7 @@ ConnectionDoctor.prototype.configure = function(credentials) {
*/ */
ConnectionDoctor.prototype.check = function() { ConnectionDoctor.prototype.check = function() {
var self = this; var self = this;
return self._q(function(resolve) { return new Promise(function(resolve) {
if (!self.credentials) { if (!self.credentials) {
throw new Error('You need to configure() the connection doctor first!'); throw new Error('You need to configure() the connection doctor first!');
} else { } else {
@ -115,7 +114,7 @@ ConnectionDoctor.prototype.check = function() {
*/ */
ConnectionDoctor.prototype._checkOnline = function() { ConnectionDoctor.prototype._checkOnline = function() {
var self = this; var self = this;
return self._q(function(resolve) { return new Promise(function(resolve) {
if (navigator.onLine) { if (navigator.onLine) {
resolve(); resolve();
} else { } else {
@ -133,7 +132,7 @@ ConnectionDoctor.prototype._checkOnline = function() {
*/ */
ConnectionDoctor.prototype._checkReachable = function(options) { ConnectionDoctor.prototype._checkReachable = function(options) {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
var socket, var socket,
error, // remember the error message error, // remember the error message
timeout, // remember the timeout object timeout, // remember the timeout object
@ -198,7 +197,7 @@ ConnectionDoctor.prototype._checkReachable = function(options) {
*/ */
ConnectionDoctor.prototype._checkImap = function() { ConnectionDoctor.prototype._checkImap = function() {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
var loggedIn = false, var loggedIn = false,
host = self.credentials.imap.host + ':' + self.credentials.imap.port, host = self.credentials.imap.host + ':' + self.credentials.imap.port,
str = self._appConfig.string; str = self._appConfig.string;
@ -248,7 +247,7 @@ ConnectionDoctor.prototype._checkImap = function() {
*/ */
ConnectionDoctor.prototype._checkSmtp = function() { ConnectionDoctor.prototype._checkSmtp = function() {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
var host = self.credentials.smtp.host + ':' + self.credentials.smtp.port, var host = self.credentials.smtp.host + ':' + self.credentials.smtp.port,
errored = false, // tracks if we need to invoke the callback at onclose or not errored = false, // tracks if we need to invoke the callback at onclose or not
str = self._appConfig.string; str = self._appConfig.string;

View File

@ -15,8 +15,7 @@ var axe = require('axe-logger'),
/** /**
* Handles database migration * Handles database migration
*/ */
function UpdateHandler($q, appConfigStore, accountStore, auth, dialog) { function UpdateHandler(appConfigStore, accountStore, auth, dialog) {
this._q = $q;
this._appConfigStorage = appConfigStore; this._appConfigStorage = appConfigStore;
this._userStorage = accountStore; this._userStorage = accountStore;
this._updateScripts = [updateV1, updateV2, updateV3, updateV4, updateV5]; this._updateScripts = [updateV1, updateV2, updateV3, updateV4, updateV5];
@ -51,7 +50,7 @@ UpdateHandler.prototype.update = function() {
*/ */
UpdateHandler.prototype._applyUpdate = function(options) { UpdateHandler.prototype._applyUpdate = function(options) {
var self = this; var self = this;
return self._q(function(resolve, reject) { return new Promise(function(resolve, reject) {
var scriptOptions, var scriptOptions,
queue = []; queue = [];

View File

@ -49,10 +49,6 @@ require('../src/js/email');
// Global mocks // Global mocks
// //
window.qMock = function(res, rej) {
return new Promise(res, rej);
};
window.resolves = function(val) { window.resolves = function(val) {
return new Promise(function(res) { return new Promise(function(res) {
res(val); res(val);

View File

@ -11,7 +11,7 @@ describe('Device Storage DAO unit tests', function() {
beforeEach(function() { beforeEach(function() {
lawnchairDaoStub = sinon.createStubInstance(LawnchairDAO); lawnchairDaoStub = sinon.createStubInstance(LawnchairDAO);
storageDao = new DeviceStorageDAO(lawnchairDaoStub, window.qMock); storageDao = new DeviceStorageDAO(lawnchairDaoStub);
}); });
afterEach(function() {}); afterEach(function() {});

View File

@ -11,7 +11,7 @@ describe('Invitation DAO unit tests', function() {
beforeEach(function() { beforeEach(function() {
restDaoStub = sinon.createStubInstance(RestDAO); restDaoStub = sinon.createStubInstance(RestDAO);
invitationDao = new InvitationDAO(restDaoStub, window.qMock); invitationDao = new InvitationDAO(restDaoStub);
}); });
describe('initialization', function() { describe('initialization', function() {

View File

@ -21,7 +21,7 @@ describe('Lawnchair DAO unit tests', function() {
var lawnchairDao; var lawnchairDao;
beforeEach(function(done) { beforeEach(function(done) {
lawnchairDao = new LawnchairDAO(qMock); lawnchairDao = new LawnchairDAO();
lawnchairDao.init(dbName).then(function() { lawnchairDao.init(dbName).then(function() {
expect(lawnchairDao._db).to.exist; expect(lawnchairDao._db).to.exist;
done(); done();

View File

@ -29,45 +29,43 @@ describe('Newsletter Service unit test', function() {
xhrMock.restore(); xhrMock.restore();
}); });
it('should not signup if user has not agreed', inject(function($rootScope) { it('should not signup if user has not agreed', function(done) {
newsletter.signup('text@example.com', false).then(function(result) { newsletter.signup('text@example.com', false).then(function(result) {
expect(result).to.be.false; expect(result).to.be.false;
expect(requests.length).to.equal(0);
done();
}); });
});
$rootScope.$apply(); it('should not signup due to invalid email address', function(done) {
expect(requests.length).to.equal(0);
}));
it('should not signup due to invalid email address', inject(function($rootScope) {
newsletter.signup('textexample.com', true).catch(function(err) { newsletter.signup('textexample.com', true).catch(function(err) {
expect(err.message).to.contain('Invalid'); expect(err.message).to.contain('Invalid');
expect(requests.length).to.equal(0);
done();
}); });
});
$rootScope.$apply(); it('should fail', function(done) {
expect(requests.length).to.equal(0);
}));
it('should fail', inject(function($rootScope) {
newsletter.signup('text@example.com', true).catch(function(err) { newsletter.signup('text@example.com', true).catch(function(err) {
expect(err).to.exist; expect(err).to.exist;
expect(requests.length).to.equal(1);
done();
}); });
requests[0].onerror('err'); requests[0].onerror('err');
$rootScope.$apply(); });
expect(requests.length).to.equal(1);
}));
it('should work', inject(function($rootScope) { it('should work', function(done) {
newsletter.signup('text@example.com', true).then(function(result) { newsletter.signup('text@example.com', true).then(function(result) {
expect(result).to.exist; expect(result).to.exist;
expect(requests.length).to.equal(1);
done();
}); });
requests[0].respond(200, { requests[0].respond(200, {
"Content-Type": "text/plain" "Content-Type": "text/plain"
}, 'foobar!'); }, 'foobar!');
$rootScope.$apply(); });
expect(requests.length).to.equal(1);
}));
}); });
}); });

View File

@ -9,7 +9,7 @@ describe('OAuth unit tests', function() {
beforeEach(function() { beforeEach(function() {
googleApiStub = sinon.createStubInstance(RestDAO); googleApiStub = sinon.createStubInstance(RestDAO);
oauth = new OAuth(qMock, googleApiStub); oauth = new OAuth(googleApiStub);
window.chrome = window.chrome || {}; window.chrome = window.chrome || {};

View File

@ -23,7 +23,7 @@ describe('Rest DAO unit tests', function() {
describe('setBaseUri', function() { describe('setBaseUri', function() {
it('should accept base uri', function() { it('should accept base uri', function() {
var baseUri = 'http://custom.com'; var baseUri = 'http://custom.com';
restDao = new RestDAO(window.qMock); restDao = new RestDAO();
expect(restDao._baseUri).to.not.exist; expect(restDao._baseUri).to.not.exist;
restDao.setBaseUri(baseUri); restDao.setBaseUri(baseUri);
expect(restDao._baseUri).to.equal(baseUri); expect(restDao._baseUri).to.equal(baseUri);

View File

@ -52,7 +52,7 @@ describe('Connection Doctor', function() {
// //
// Setup SUT // Setup SUT
// //
doctor = new ConnectionDoctor(qMock, appConfig); doctor = new ConnectionDoctor(appConfig);
doctor.configure(credentials); doctor.configure(credentials);
doctor._imap = imapStub; doctor._imap = imapStub;
doctor._smtp = smtpStub; doctor._smtp = smtpStub;

View File

@ -17,7 +17,7 @@ describe('UpdateHandler', function() {
userStorageStub = sinon.createStubInstance(DeviceStorageDAO); userStorageStub = sinon.createStubInstance(DeviceStorageDAO);
authStub = sinon.createStubInstance(Auth); authStub = sinon.createStubInstance(Auth);
dialogStub = sinon.createStubInstance(Dialog); dialogStub = sinon.createStubInstance(Dialog);
updateHandler = new UpdateHandler(qMock, appConfigStorageStub, userStorageStub, authStub, dialogStub); updateHandler = new UpdateHandler(appConfigStorageStub, userStorageStub, authStub, dialogStub);
}); });
afterEach(function() { afterEach(function() {