Skip to content

Commit

Permalink
Add upsert and save transaction proof of concept
Browse files Browse the repository at this point in the history
Supports #33
  • Loading branch information
timwis committed Jan 11, 2020
1 parent 21aac21 commit 4dcc8b7
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
33 changes: 33 additions & 0 deletions backend/lib/GitSheets.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,39 @@ module.exports = class GitSheets {
await this.git.branch({D: true}, dstRef); // force delete in case srcRef is not checked out
}

async createTransaction (parentRef) {
const treeObject = await this._createTreeFromRef(parentRef);
const gitSheets = this;

// TODO: Use a class or something, rather than generating this code each transaction
return {
upsert: function upsert (path, data) {
const contents = gitSheets._serialize(data);
// TODO: Wrap errors
return treeObject.writeChild(`${path}.toml`, contents);
},
async save (saveToBranch = parentRef) {
// TODO: Wrap errors
const treeHash = await treeObject.write();

if (saveToBranch && saveToBranch === parentRef) { // TODO: check if branch exists instead
await gitSheets._saveTreeToExistingBranch({
treeHash,
branch: saveToBranch,
msg: 'import to existing branch',
});
} else if (saveToBranch) {
await gitSheets._saveTreeToNewBranch({
treeHash,
parentRef,
branch: saveToBranch,
msg: 'import to new branch',
});
}
},
};
}

_isDataBlob ([key, blob]) {
return !key.startsWith('.gitsheets/') && key.endsWith('.toml') && blob instanceof BlobObject;
}
Expand Down
26 changes: 26 additions & 0 deletions backend/test/GitSheets.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,32 @@ describe('GitSheets lib', () => {
.toThrow(MergeError);
});
});

describe.only('Transaction', () => {
it('upserts on top of branch', async () => {
const txn = await gitSheets.createTransaction('master');
await txn.upsert('1', sampleData.initial[0]);
await txn.upsert('2', sampleData.initial[1]);
await txn.save();

const response = await gitSheets.git.lsTree('master');
const tree = parseTree(response);

const blobs = tree.filter((item) => item.type === 'blob');
expect(blobs.length).toBe(2);

await Promise.all(blobs.map(verifyBlob));

async function verifyBlob ({ hash, file }) {
const sampleDataItem = sampleData.initial.find((item) => item.id === file.substr(0, file.length - 5));
expect(sampleDataItem).toBeDefined();

const contents = await gitSheets.git.catFile('blob', hash);
const data = gitSheets._deserialize(contents);
expect(data).toEqual(sampleDataItem);
}
})
})
});

function parseTree (treeOutput) {
Expand Down

0 comments on commit 4dcc8b7

Please sign in to comment.