Skip to content

Commit

Permalink
🐛 fix algolia indexing error when deleting an unpublished post, impro…
Browse files Browse the repository at this point in the history
…ve indexing logic exhaustiveness
  • Loading branch information
ikesau committed Apr 12, 2024
1 parent e8cda62 commit ba2346b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
10 changes: 8 additions & 2 deletions adminSiteServer/apiRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2316,7 +2316,13 @@ async function indexAndBakeGdocIfNeccesary(
.with(GdocPublishingAction.SavingDraft, lodash.noop)
.with(GdocPublishingAction.Publishing, async () => {
if (isGdocPost) {
await indexIndividualGdocPost(nextJson, trx, prevGdoc.slug)
await indexIndividualGdocPost(
nextJson,
trx,
// If the gdoc is being published for the first time, prevGdoc.slug will be undefined
// In that case, we pass nextJson.slug to see if it has any page views (i.e. from WP)
prevGdoc.slug || nextJson.slug
)
}
await triggerStaticBuild(user, `${action} ${nextJson.slug}`)
})
Expand Down Expand Up @@ -2393,7 +2399,7 @@ deleteRouteWithRWTransaction(apiRouter, "/gdocs/:id", async (req, res, trx) => {
await trx.table(PostsGdocsLinksTableName).where({ sourceId: id }).delete()
await trx.table(PostsGdocsXImagesTableName).where({ gdocId: id }).delete()
await trx.table(PostsGdocsTableName).where({ id }).delete()
if (checkIsGdocPostExcludingFragments(gdoc)) {
if (gdoc.published && checkIsGdocPostExcludingFragments(gdoc)) {
await removeIndividualGdocPostFromIndex(gdoc)
}
await triggerStaticBuild(res.locals.user, `Deleting ${gdoc.slug}`)
Expand Down
19 changes: 12 additions & 7 deletions baker/algolia/algoliaUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -291,18 +291,23 @@ export async function indexIndividualGdocPost(
await getExistingRecordsForSlug(index, indexedSlug)

try {
console.log("Updating Algolia index for Gdoc post", gdoc.slug)

if (existingRecordsForPost.length === records.length) {
// If the number of chunks is the same, we can just update the records
await index.saveObjects(records)
} else {
if (
existingRecordsForPost.length &&
existingRecordsForPost.length !== records.length
) {
// If the number of chunks has changed, we need to delete the old records first
console.log(
"Deleting Algolia index records for Gdoc post",
indexedSlug
)
await index.deleteObjects(
existingRecordsForPost.map((r) => r.objectID)
)
await index.saveObjects(records)
}
console.log("Updating Algolia index for Gdoc post", gdoc.slug)
// If the number of records hasn't changed, the records' objectIDs will be the same
// so this will safely overwrite them or create new ones
await index.saveObjects(records)
console.log("Updated Algolia index for Gdoc post", gdoc.slug)
} catch (e) {
console.error("Error indexing Gdoc post to Algolia: ", e)
Expand Down

0 comments on commit ba2346b

Please sign in to comment.