diff --git a/server/services/backlinks.js b/server/services/backlinks.js index 74c915b5d0..4a3a0da595 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 83c09f6705..8487f81ea8 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();