Add challengeMap migrations

This commit is contained in:
Berkeley Martinez
2016-02-09 13:22:43 -08:00
parent 9913d8de92
commit 07d54a455c
3 changed files with 72 additions and 1 deletions

View File

@ -148,6 +148,16 @@
"default": false, "default": false,
"description": "Campers is full stack certified" "description": "Campers is full stack certified"
}, },
"isChallengeMapMigrated": {
"type": "boolean",
"default": false,
"description": "Migrate completedChallenges array to challenge map"
},
"challengeMap": {
"type": "object",
"default": {},
"description": "A map by id of all the user completed challenges"
},
"completedChallenges": { "completedChallenges": {
"type": [ "type": [
{ {

View File

@ -47,7 +47,8 @@
"./middlewares/express-rx": {}, "./middlewares/express-rx": {},
"./middlewares/jade-helpers": {}, "./middlewares/jade-helpers": {},
"./middlewares/global-locals": {}, "./middlewares/global-locals": {},
"./middlewares/revision-helpers": {} "./middlewares/revision-helpers": {},
"./middlewares/migrate-completed-challenges": {}
}, },
"routes": { "routes": {
}, },

View File

@ -0,0 +1,60 @@
import { Observable, Scheduler } from 'rx';
import debug from 'debug';
const log = debug('freecc:migrate');
// buildChallengeMap(
// userId: String,
// completedChallenges: Object[],
// User: User
// ) => Observable
function buildChallengeMap(userId, completedChallenges = [], User) {
return Observable.from(
completedChallenges,
null,
null,
Scheduler.default
)
.reduce((challengeMap, challenge) => {
const id = challenge.id || challenge._id;
challenge = challenge && typeof challenge.toJSON === 'function' ?
challenge.toJSON() :
challenge;
challengeMap[id] = challenge;
return challengeMap;
}, {})
.flatMap(challengeMap => {
const updateData = {
'$set': {
challengeMap,
isChallengeMapMigrated: true
}
};
return Observable.fromNodeCallback(User.updateAll, User)(
{ id: userId },
updateData,
{ allowExtendedOperators: true }
);
});
}
export default function migrateCompletedChallenges() {
return ({ user, app }, res, next) => {
const User = app.models.User;
if (!user || user.isChallengeMapMigrated) {
return next();
}
return buildChallengeMap(
user.id.toString(),
user.completedChallenges,
User
)
.subscribe(
count => log('documents update', count),
// errors go here
next,
next
);
};
}