Removed invalid entities from results

refs https://github.com/TryGhost/Arch/issues/47

This change allows us to throw errors when instantiating invalid entities,
whilst not breaking things when we have bad data in the database. What we can
do is act as if the bad rows are not present, whilst surfacing an error in
sentry to alert us to such cases.
This commit is contained in:
Fabien "egg" O'Carroll 2023-08-21 13:21:35 +01:00 committed by Fabien 'egg' O'Carroll
parent 27bfa30f97
commit c98bf80248

View File

@ -1,4 +1,6 @@
const logger = require('@tryghost/logging');
const Collection = require('@tryghost/collections').Collection;
const sentry = require('../../../shared/sentry');
/**
* @typedef {import('@tryghost/collections/src/CollectionRepository')} CollectionRepository
*/
@ -61,28 +63,35 @@ module.exports = class BookshelfCollectionsRepository {
withRelated: ['collectionPosts']
});
return await Promise.all(models.map(model => this.#modelToCollection(model)));
return (await Promise.all(models.map(model => this.#modelToCollection(model)))).filter(entity => !!entity);
}
#modelToCollection(model) {
async #modelToCollection(model) {
const json = model.toJSON();
let filter = json.filter;
if (json.type === 'automatic' && typeof filter !== 'string') {
filter = '';
}
return Collection.create({
id: json.id,
slug: json.slug,
title: json.title,
description: json.description,
filter: filter,
type: json.type,
featureImage: json.feature_image,
posts: json.collectionPosts.map(collectionPost => collectionPost.post_id),
createdAt: json.created_at,
updatedAt: json.updated_at
});
try {
return await Collection.create({
id: json.id,
slug: json.slug,
title: json.title,
description: json.description,
filter: filter,
type: json.type,
featureImage: json.feature_image,
posts: json.collectionPosts.map(collectionPost => collectionPost.post_id),
createdAt: json.created_at,
updatedAt: json.updated_at
});
} catch (err) {
logger.error(err);
sentry.captureException(err);
return null;
}
}
/**