Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@joeljuca
Last active May 12, 2020 10:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeljuca/67bfbdcf0aa42418eed4c0246f5fe2a4 to your computer and use it in GitHub Desktop.
Save joeljuca/67bfbdcf0aa42418eed4c0246f5fe2a4 to your computer and use it in GitHub Desktop.
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;
};
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