Skip to content

Commit

Permalink
Replace Async occurrences with built in methods
Browse files Browse the repository at this point in the history
  • Loading branch information
XVincentX committed Nov 3, 2017
1 parent 708d87e commit 5efe867
Show file tree
Hide file tree
Showing 23 changed files with 1,134 additions and 1,118 deletions.
20 changes: 18 additions & 2 deletions lib/db.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
const logger = require('./logger').db;
const redisCommands = require('redis-commands');
require('util.promisify/shim')(); // NOTE: shim for native node 8.0 uril.promisify
const util = require('util');
let db;

module.exports = function () {
Expand All @@ -12,9 +15,22 @@ module.exports = function () {
// designed for demo and test scenarious to avoid having real Redis instance
const emulate = process.argv[2] === 'emulate' || redisOptions.emulate;

const Redis = require(emulate ? 'ioredis-mock' : 'ioredis');
if (emulate) {
const redis = require('fakeredis');
promisify(redis.RedisClient.prototype, redisCommands.list.filter(c => c.toLowerCase() !== 'multi'));
promisify(redis.Multi.prototype, ['exec', 'execAtomic']);
db = redis.createClient(redisOptions);
} else {
db = new (require('ioredis'))(redisOptions);
}

db = new Redis(redisOptions);
function promisify (obj, methods) {
methods.forEach((method) => {
if (obj[method]) {
obj[method] = util.promisify(obj[method]);
}
});
}

db.on('ready', function () {
logger.debug('Redis is ready');
Expand Down
8 changes: 4 additions & 4 deletions lib/services/authorization-codes/authorization-code.dao.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ const authCodeNamespace = 'auth-code';
dao.save = function (code) {
// key for the code hash table
const redisCodeKey = config.systemConfig.db.redis.namespace.concat('-', authCodeNamespace).concat(':', code.id);
return db.hmsetAsync(redisCodeKey, code);
return db.hmset(redisCodeKey, code);
};

dao.find = function (criteria) {
return db.hgetallAsync(config.systemConfig.db.redis.namespace.concat('-', authCodeNamespace).concat(':', criteria.id))
return db.hgetall(config.systemConfig.db.redis.namespace.concat('-', authCodeNamespace).concat(':', criteria.id))
.then((code) => {
if (!code) {
return null;
Expand All @@ -31,11 +31,11 @@ dao.find = function (criteria) {
};

dao.get = function (id) {
return db.hgetallAsync(config.systemConfig.db.redis.namespace.concat('-', authCodeNamespace).concat(':', id));
return db.hgetall(config.systemConfig.db.redis.namespace.concat('-', authCodeNamespace).concat(':', id));
};

dao.remove = function (id) {
return db.delAsync(config.systemConfig.db.redis.namespace.concat('-', authCodeNamespace).concat(':', id));
return db.del(config.systemConfig.db.redis.namespace.concat('-', authCodeNamespace).concat(':', id));
};

module.exports = dao;
78 changes: 39 additions & 39 deletions lib/services/consumers/application.dao.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,32 @@ dao.insert = function (app) {
const userAppsHashKey = config.systemConfig.db.redis.namespace.concat('-', userAppsNamespace).concat(':', app.userId);

return db
.multi()
.hmset(appHashKey, app)
.sadd(userAppsHashKey, app.id)
.execAsync()
.then(res => res.every(val => val));
.multi()
.hmset(appHashKey, app)
.sadd(userAppsHashKey, app.id)
.exec()
.then(res => res.every(val => val));
};

dao.update = function (id, props) {
// key for the app hash table
const appHashKey = config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':', id);

return db
.hmsetAsync(appHashKey, props)
.then(function (res) {
return !!res;
});
.hmset(appHashKey, props)
.then(function (res) {
return !!res;
});
};

dao.findAll = function (query) {
const key = config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':');
const startFrom = query.start || 0;
return db.scanAsync(startFrom, 'MATCH', key + '*', 'COUNT', '100').then(resp => {
return db.scan(startFrom, 'MATCH', key + '*', 'COUNT', '100').then(resp => {
const nextKey = resp[0];
const appKeys = resp[1];
if (!appKeys || appKeys.length === 0) return Promise.resolve({apps: [], nextKey: 0});
const promises = appKeys.map(key => db.hgetallAsync(key));
if (!appKeys || appKeys.length === 0) return Promise.resolve({ apps: [], nextKey: 0 });
const promises = appKeys.map(key => db.hgetall(key));
return Promise.all(promises).then(apps => {
return {
apps,
Expand All @@ -52,58 +52,58 @@ dao.findAll = function (query) {
};

dao.get = function (id) {
return db.hgetallAsync(config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':', id))
.then(function (app) {
if (!app || !Object.keys(app).length) {
return false;
} else return app;
});
return db.hgetall(config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':', id))
.then(function (app) {
if (!app || !Object.keys(app).length) {
return false;
} else return app;
});
};

dao.getAll = function (userId) {
return this.getAllAppIdsByUser(userId)
.then(appIds => {
return Promise.all(appIds.map(this.get))
.then(apps => apps.filter(app => app !== false));
});
.then(appIds => {
return Promise.all(appIds.map(this.get))
.then(apps => apps.filter(app => app !== false));
});
};

dao.getAllAppIdsByUser = function (userId) {
return db.smembersAsync(config.systemConfig.db.redis.namespace.concat('-', userAppsNamespace).concat(':', userId));
return db.smembers(config.systemConfig.db.redis.namespace.concat('-', userAppsNamespace).concat(':', userId));
};

dao.activate = function (id) {
return db.hmsetAsync(config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':', id), ['isActive', 'true', 'updatedAt', String(new Date())]);
return db.hmset(config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':', id), ['isActive', 'true', 'updatedAt', String(new Date())]);
};

dao.deactivate = function (id) {
return db.hmsetAsync(config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':', id), ['isActive', 'false', 'updatedAt', String(new Date())]);
return db.hmset(config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':', id), ['isActive', 'false', 'updatedAt', String(new Date())]);
};

dao.deactivateAll = function (userId) {
return this.getAllAppIdsByUser(userId)
.then(appIds => {
const deactivateAppPromises = appIds.map(appId => this.deactivate(appId));
return Promise.all(deactivateAppPromises);
});
.then(appIds => {
const deactivateAppPromises = appIds.map(appId => this.deactivate(appId));
return Promise.all(deactivateAppPromises);
});
};

dao.remove = function (id, userId) {
return db
.multi()
.del(config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':', id))
.srem(config.systemConfig.db.redis.namespace.concat('-', userAppsNamespace).concat(':', userId), id)
.execAsync()
.then(responses => responses.every(res => res));
.multi()
.del(config.systemConfig.db.redis.namespace.concat('-', appNamespace).concat(':', id))
.srem(config.systemConfig.db.redis.namespace.concat('-', userAppsNamespace).concat(':', userId), id)
.exec()
.then(responses => responses.every(res => res));
};

dao.removeAll = function (userId) {
return this.getAllAppIdsByUser(userId)
.then(appIds => {
const removeAppPromises = appIds.map(appId => this.remove(appId, userId));
return Promise.all(removeAppPromises)
.then(responses => responses.every(res => res));
});
.then(appIds => {
const removeAppPromises = appIds.map(appId => this.remove(appId, userId));
return Promise.all(removeAppPromises)
.then(responses => responses.every(res => res));
});
};

module.exports = dao;
18 changes: 9 additions & 9 deletions lib/services/consumers/user.dao.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ dao.insert = function (user) {
.multi()
.hmset(redisUserKey, user)
.sadd(redisUsernameSetKey, user.id)
.execAsync()
.exec()
.then(res => res.every(val => val));
};

dao.getUserById = function (userId) {
return db.hgetallAsync(config.systemConfig.db.redis.namespace.concat('-', userNamespace).concat(':', userId))
return db.hgetall(config.systemConfig.db.redis.namespace.concat('-', userNamespace).concat(':', userId))
.then(function (user) {
if (!user || !Object.keys(user).length) {
return false;
Expand All @@ -35,11 +35,11 @@ dao.getUserById = function (userId) {
dao.findAll = function (query) {
const startFrom = query.start || 0;
const key = config.systemConfig.db.redis.namespace.concat('-', userNamespace).concat(':');
return db.scanAsync(startFrom, 'MATCH', key + '*', 'COUNT', '100').then(resp => {
return db.scan(startFrom, 'MATCH', key + '*', 'COUNT', '100').then(resp => {
const nextKey = resp[0];
const userKeys = resp[1];
if (!userKeys || userKeys.length === 0) return Promise.resolve({ users: [], nextKey: 0 });
const promises = userKeys.map(key => db.hgetallAsync(key));
const promises = userKeys.map(key => db.hgetall(key));
return Promise.all(promises).then(users => {
return {
users,
Expand All @@ -50,7 +50,7 @@ dao.findAll = function (query) {
};

dao.find = function (username) {
return db.smembersAsync(config.systemConfig.db.redis.namespace.concat('-', usernameNamespace).concat(':', username))
return db.smembers(config.systemConfig.db.redis.namespace.concat('-', usernameNamespace).concat(':', username))
.then(function (Ids) {
if (Ids && Ids.length !== 0) {
return Ids[0];
Expand All @@ -62,16 +62,16 @@ dao.update = function (userId, props) {
// key for the user in redis
const redisUserKey = config.systemConfig.db.redis.namespace.concat('-', userNamespace).concat(':', userId);
return db
.hmsetAsync(redisUserKey, props)
.hmset(redisUserKey, props)
.then(res => !!res);
};

dao.activate = function (id) {
return db.hmsetAsync(config.systemConfig.db.redis.namespace.concat('-', userNamespace).concat(':', id), ['isActive', 'true', 'updatedAt', String(new Date())]);
return db.hmset(config.systemConfig.db.redis.namespace.concat('-', userNamespace).concat(':', id), ['isActive', 'true', 'updatedAt', String(new Date())]);
};

dao.deactivate = function (id) {
return db.hmsetAsync(config.systemConfig.db.redis.namespace.concat('-', userNamespace).concat(':', id), ['isActive', 'false', 'updatedAt', String(new Date())]);
return db.hmset(config.systemConfig.db.redis.namespace.concat('-', userNamespace).concat(':', id), ['isActive', 'false', 'updatedAt', String(new Date())]);
};

dao.remove = function (userId) {
Expand All @@ -84,7 +84,7 @@ dao.remove = function (userId) {
.multi()
.del(config.systemConfig.db.redis.namespace.concat('-', userNamespace).concat(':', userId))
.srem(config.systemConfig.db.redis.namespace.concat('-', usernameNamespace).concat(':', user.username), userId)
.execAsync()
.exec()
.then(replies => replies.every(res => res));
});
};
Expand Down
38 changes: 19 additions & 19 deletions lib/services/credentials/credential.dao.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ dao.insertScopes = function (_scopes) {
_scopes.forEach(el => { scopes[el] = 'true'; });
} else scopes[_scopes] = 'true';

return db.hmsetAsync(scopeDbKey, scopes);
return db.hmset(scopeDbKey, scopes);
};

dao.associateCredentialWithScopes = function (id, type, scopes) {
Expand All @@ -24,7 +24,7 @@ dao.associateCredentialWithScopes = function (id, type, scopes) {
}

scopes = Array.isArray(scopes) ? scopes : [scopes];
const associationPromises = scopes.map(scope => db.hsetAsync(buildScopeKey(scope), credentialKey, 'true'));
const associationPromises = scopes.map(scope => db.hset(buildScopeKey(scope), credentialKey, 'true'));

return Promise.all(associationPromises)
.catch(() => Promise.reject(new Error('failed to associate credential with scopes in db'))); // TODO: replace with server error
Expand All @@ -33,7 +33,7 @@ dao.associateCredentialWithScopes = function (id, type, scopes) {
dao.dissociateCredentialFromScopes = function (id, type, scopes) {
const credentialKey = buildIdKey(type, id);
scopes = Array.isArray(scopes) ? scopes : [scopes];
const dissociationPromises = scopes.map(scope => db.hdelAsync(buildScopeKey(scope), credentialKey));
const dissociationPromises = scopes.map(scope => db.hdel(buildScopeKey(scope), credentialKey));

return Promise.all(dissociationPromises)
.catch(() => Promise.reject(new Error('failed to dissociate credential with scopes in db'))); // TODO: replace with server error
Expand All @@ -51,7 +51,7 @@ dao.removeScopes = function (scopes) {

// Get the list of ids with scopes to be removed, and remove scope-ids association
scopes.forEach(scope => {
getScopeCredentialPromises.push(db.hgetallAsync(buildScopeKey(scope)));
getScopeCredentialPromises.push(db.hgetall(buildScopeKey(scope)));
removeScopesTransaction = removeScopesTransaction.del(buildScopeKey(scope));
});

Expand All @@ -72,7 +72,7 @@ dao.removeScopes = function (scopes) {

// Get dissociation promises for the id-scopes combination and promises to update credentials to remove scope
for (const credentialId in credentialIdToScopes) {
getCredentialPromises.push(db.hgetallAsync(credentialId));
getCredentialPromises.push(db.hgetall(credentialId));
}

return Promise.all(getCredentialPromises)
Expand All @@ -90,19 +90,19 @@ dao.removeScopes = function (scopes) {
}
});

return removeScopesTransaction.execAsync()
return removeScopesTransaction.exec()
.then(res => res[0]); // .del may yield 0 if a scope wasn't assigned to any credential
});
});
};

dao.existsScope = function (scope) {
return db.hgetAsync(scopeDbKey, scope)
return db.hget(scopeDbKey, scope)
.then(res => !!res);
};

dao.getAllScopes = function () {
return db.hgetallAsync(scopeDbKey)
return db.hgetall(scopeDbKey)
.then(res => {
return res ? Object.keys(res) : null;
});
Expand All @@ -115,16 +115,16 @@ dao.insertCredential = function (id, type, credentialObj) {
if (type === 'key-auth') {
return Promise.all([
// build relation consumerId -> [key1, key2]
db.saddAsync(buildIdKey(type, credentialObj.consumerId), id),
db.sadd(buildIdKey(type, credentialObj.consumerId), id),
// store key-auth keyid -> credentialObj
db.hmsetAsync(buildIdKey(type, id), credentialObj)
db.hmset(buildIdKey(type, id), credentialObj)
]);
}
return db.hmsetAsync(buildIdKey(type, id), credentialObj);
return db.hmset(buildIdKey(type, id), credentialObj);
};

dao.getCredential = function (id, type) {
return db.hgetallAsync(buildIdKey(type, id)).then(credential => {
return db.hgetall(buildIdKey(type, id)).then(credential => {
if (!credential) return null;
credential.isActive = credential.isActive === 'true'; // Redis has no bool type, manual conversion
credential.type = type;
Expand All @@ -133,15 +133,15 @@ dao.getCredential = function (id, type) {
};

dao.activateCredential = function (id, type) {
return db.hsetAsync(buildIdKey(type, id), ['isActive', 'true', 'updatedAt', String(new Date())]);
return db.hset(buildIdKey(type, id), ['isActive', 'true', 'updatedAt', String(new Date())]);
};

dao.deactivateCredential = function (id, type) {
return db.hsetAsync(buildIdKey(type, id), ['isActive', 'false', 'updatedAt', String(new Date())]);
return db.hset(buildIdKey(type, id), ['isActive', 'false', 'updatedAt', String(new Date())]);
};

dao.removeCredential = function (id, type) {
return db.delAsync(buildIdKey(type, id));
return db.del(buildIdKey(type, id));
};

dao.removeAllCredentials = function (id) {
Expand All @@ -151,24 +151,24 @@ dao.removeAllCredentials = function (id) {
credentialTypes.forEach((type) => {
if (type === 'key-auth') {
// id in this call is actually consumerId, so we need to get all referenced keyIds
awaitAllPromises.push(db.smembersAsync(buildIdKey(type, id)).then(ids => {
awaitAllPromises.push(db.smembers(buildIdKey(type, id)).then(ids => {
ids.map(keyId => {
dbTransaction.delAsync(buildIdKey(type, keyId));
dbTransaction.del(buildIdKey(type, keyId));
});
}));
} else {
dbTransaction.del(buildIdKey(type, id));
}
});

return Promise.all(awaitAllPromises).then(() => dbTransaction.execAsync());
return Promise.all(awaitAllPromises).then(() => dbTransaction.exec());
};

dao.getAllCredentials = function (consumerId) {
const credentialTypes = Object.keys(config.models.credentials);
const awaitAllPromises = credentialTypes.map(type => {
if (type === 'key-auth') { // TODO: replace with separate implementation per type instead of ifs
return db.smembersAsync(buildIdKey(type, consumerId)).then(keyIds => {
return db.smembers(buildIdKey(type, consumerId)).then(keyIds => {
// 1-* relation, finding all key-auth credentials (consumerid => [KeyId1, KeyId2, ..., KeyIdN])
return Promise.all(keyIds.map(keyId => {
return this.getCredential(keyId, type);
Expand Down
Loading

0 comments on commit 5efe867

Please sign in to comment.