Cleaner CollectionModel code

This commit is contained in:
djmaze 2020-10-18 19:36:57 +02:00
parent ddc866735c
commit 76648f04ae
2 changed files with 19 additions and 20 deletions

View file

@ -12,21 +12,19 @@ export class AbstractCollectionModel extends Array
// props[@Count] // props[@Count]
} }
static getFromJSON(object, name) { /**
return object && 'Collection/'+name === object['@Object'] && Array.isArray(object['@Collection']) * @static
? object['@Collection'] * @param {FetchJson} json
: null; * @returns {*CollectionModel}
} */
static reviveFromJson(json, itemCallback) {
static reviveFromJson(object, itemCallback) {
// FolderCollectionModel => FolderCollection // FolderCollectionModel => FolderCollection
// AttachmentCollectionModel => AttachmentCollection // AttachmentCollectionModel => AttachmentCollection
// MessageCollectionModel => MessageCollection // MessageCollectionModel => MessageCollection
const name = this.name.replace('Model', ''), if (json && 'Collection/'+this.name.replace('Model', '') === json['@Object']
collection = this.getFromJSON(object, name); && Array.isArray(json['@Collection'])) {
if (collection) { const result = new this(json);
const result = new this(object); json['@Collection'].forEach(item => {
collection.forEach(item => {
item && itemCallback && (item = itemCallback(item, result)); item && itemCallback && (item = itemCallback(item, result));
item && result.push(item); item && result.push(item);
}); });

View file

@ -10,14 +10,15 @@ export class AttachmentCollectionModel extends AbstractCollectionModel
* @returns {AttachmentCollectionModel} * @returns {AttachmentCollectionModel}
*/ */
static reviveFromJson(items) { static reviveFromJson(items) {
let result = new AttachmentCollectionModel; let cb = attachment => AttachmentModel.newInstanceFromJson(attachment),
items = this.getFromJSON(items, 'AttachmentCollection') || items; result = super.reviveFromJson(items, cb);
Array.isArray(items) && items.forEach(attachment => { if (!result) {
attachment = AttachmentModel.newInstanceFromJson(attachment); result = new AttachmentCollectionModel;
if (attachment) { Array.isArray(items) && items.forEach(attachment => {
result.push(attachment); attachment = cb(attachment);
} attachment && result.push(attachment);
}); });
}
return result; return result;
} }