Last active
May 12, 2020 10:22
-
-
Save joeljuca/67bfbdcf0aa42418eed4c0246f5fe2a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type DocumentVersion = { | |
// CouchDB's own ID system | |
_id: string; | |
// Your document history ID - the same across all versions of a document | |
historyId: string; | |
// The _id of the ancestor document (undefined if first version) | |
parentId: string; | |
// Indicates if this version is archived or not | |
archived: boolean; | |
// Utility flags. Might be useful in future implementations of reconciliation | |
// algorithms, or the construction of a changelog feature | |
createdAt: Date; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const saveDocumentVersion = async ({ _id, doc }) => { | |
// Avoid saving a document version that's already archived | |
delete doc.archived; | |
const newDoc = { | |
...doc, | |
createdAt: new Date().toISOString(), | |
}; | |
let parentDoc; | |
if (doc.parentId) { | |
parentDoc = await loadDocument(doc.parentId); | |
} | |
if (parentDoc) { | |
// Rely on parentDoc to get historyId and parentId | |
newDoc.historyId = parentDoc.historyId; | |
newDoc.parentId = parentDoc._id; | |
} else { | |
newDoc.historyId = await generateHistoryId(); | |
} | |
const savedDoc = await saveDocument(newDoc); | |
// Archives the parent document only after new version is saved | |
// (sends `parentDoc.archived = true` to CouchDB) | |
if (parentDoc) { | |
await archiveDocument(parentDoc); | |
} | |
return savedDoc; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment