From d4bb04e921ee5239c9ff00ec89bb292d62f951d5 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 29 Dec 2020 10:32:09 -0800 Subject: [PATCH] fix: Handle linked documents destroyed when document is published closes #1739 --- server/services/backlinks.js | 4 ++- server/services/backlinks.test.js | 50 +++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/server/services/backlinks.js b/server/services/backlinks.js index 74c915b5d..4a3a0da59 100644 --- a/server/services/backlinks.js +++ b/server/services/backlinks.js @@ -17,7 +17,9 @@ export default class Backlinks { await Promise.all( linkIds.map(async (linkId) => { const linkedDocument = await Document.findByPk(linkId); - if (linkedDocument.id === event.documentId) return; + if (!linkedDocument || linkedDocument.id === event.documentId) { + return; + } await Backlink.findOrCreate({ where: { diff --git a/server/services/backlinks.test.js b/server/services/backlinks.test.js index 83c09f670..8487f81ea 100644 --- a/server/services/backlinks.test.js +++ b/server/services/backlinks.test.js @@ -9,6 +9,56 @@ const Backlinks = new BacklinksService(); beforeEach(() => flushdb()); beforeEach(jest.resetAllMocks); +describe("documents.publish", () => { + test("should create new backlink records", async () => { + const otherDocument = await buildDocument(); + const document = await buildDocument({ + text: `[this is a link](${otherDocument.url})`, + }); + + await Backlinks.on({ + name: "documents.publish", + documentId: document.id, + collectionId: document.collectionId, + teamId: document.teamId, + actorId: document.createdById, + }); + + const backlinks = await Backlink.findAll({ + where: { reverseDocumentId: document.id }, + }); + + expect(backlinks.length).toBe(1); + }); + + test("should not fail when linked document is destroyed", async () => { + const otherDocument = await buildDocument(); + await otherDocument.destroy(); + + const document = await buildDocument({ + version: null, + text: `[ ] checklist item`, + }); + + document.text = `[this is a link](${otherDocument.url})`; + await document.save(); + + await Backlinks.on({ + name: "documents.publish", + documentId: document.id, + collectionId: document.collectionId, + teamId: document.teamId, + actorId: document.createdById, + }); + + const backlinks = await Backlink.findAll({ + where: { reverseDocumentId: document.id }, + }); + + expect(backlinks.length).toBe(0); + }); +}); + describe("documents.update", () => { test("should not fail on a document with no previous revisions", async () => { const otherDocument = await buildDocument();