feat: Auto update titles in linked documents (#1233)

* feat: Auto update titles in linked documents

* Add spec
This commit is contained in:
Tom Moor
2020-04-19 21:58:42 -07:00
committed by GitHub
parent ee5ae140c3
commit c526adf292
4 changed files with 159 additions and 8 deletions

View File

@@ -3,6 +3,7 @@ import { difference } from 'lodash';
import type { DocumentEvent } from '../events';
import { Document, Revision, Backlink } from '../models';
import parseDocumentIds from '../../shared/utils/parseDocumentIds';
import slugify from '../utils/slugify';
export default class Backlinks {
async on(event: DocumentEvent) {
@@ -50,6 +51,7 @@ export default class Backlinks {
const addedLinkIds = difference(currentLinkIds, previousLinkIds);
const removedLinkIds = difference(previousLinkIds, currentLinkIds);
// add any new backlinks that were created
await Promise.all(
addedLinkIds.map(async linkId => {
const linkedDocument = await Document.findByPk(linkId);
@@ -67,6 +69,7 @@ export default class Backlinks {
})
);
// delete any backlinks that were removed
await Promise.all(
removedLinkIds.map(async linkId => {
const document = await Document.findByPk(linkId);
@@ -78,6 +81,39 @@ export default class Backlinks {
});
})
);
if (currentRevision.title === previousRevision.title) {
break;
}
// update any link titles in documents that lead to this one
const backlinks = await Backlink.findAll({
where: {
documentId: event.documentId,
},
include: [{ model: Document, as: 'reverseDocument' }],
});
await Promise.all(
backlinks.map(async backlink => {
const previousUrl = `/doc/${slugify(previousRevision.title)}-${
document.urlId
}`;
// find links in the other document that lead to this one and have
// the old title as anchor text. Go ahead and update those to the
// new title automatically
backlink.reverseDocument.text = backlink.reverseDocument.text.replace(
`[${previousRevision.title}](${previousUrl})`,
`[${document.title}](${document.url})`
);
await backlink.reverseDocument.save({
silent: true,
hooks: false,
});
})
);
break;
}
case 'documents.delete': {