fix invalid push devices

This commit is contained in:
Matteo Pagliazzi
2020-03-01 21:49:52 +01:00
parent 6deee0ffc8
commit 3f5ee32684
5 changed files with 89 additions and 10 deletions

View File

@@ -1,4 +1,5 @@
import mongoose from 'mongoose';
import _ from 'lodash';
import baseModel from '../libs/baseModel';
const { Schema } = mongoose;
@@ -19,4 +20,30 @@ schema.plugin(baseModel, {
_id: false,
});
/**
* Remove invalid data from an array of push devices.
* Fix for https://github.com/HabitRPG/habitica/issues/11805
* and https://github.com/HabitRPG/habitica/issues/11868
* Called by user's post init hook (models/user/hooks.js)
*/
schema.statics.cleanupCorruptData = function cleanupCorruptPushDevicesData (pushDevices) {
if (!pushDevices) return pushDevices;
let filteredPushDevices = pushDevices.filter(pushDevice => {
// Exclude push devices with a nullish value, no id or no type
if (!pushDevice || !pushDevice.regId || !pushDevice.type) return false;
return true;
});
// Remove duplicate push devices
// can be caused by a race condition when adding a new push device
filteredPushDevices = _.uniqWith(filteredPushDevices, (val, otherVal) => {
if (val.regId === otherVal.regId && val.type === otherVal.type) return true;
return false;
});
return filteredPushDevices;
};
export const model = mongoose.model('PushDevice', schema);