From 3041ffc60ab245a27e7315baf1b0b8d184c7bb1d Mon Sep 17 00:00:00 2001 From: Andre Staltz Date: Sun, 9 Apr 2023 11:21:25 +0300 Subject: [PATCH] create() has an easy API to create tangles --- lib/plugin.js | 22 +++++++++++++++++++++- test/create.test.js | 22 ++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/lib/plugin.js b/lib/plugin.js index 0f02b6d..6890edb 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -199,6 +199,24 @@ exports.init = function initDB(peer, config) { } } + function populateTangle(tangleId) { + const map = new Map() + for (const rec of records()) { + if (rec.hash === tangleId || rec.msg.metadata.tangles?.[tangleId]) { + map.set(rec.hash, rec.msg) + } + } + return map + } + + function populateTangles(tangleIds) { + const tangles = {} + for (const tangleId of tangleIds) { + tangles[tangleId] = populateTangle(tangleId) + } + return tangles + } + function create(opts, cb) { const keys = opts.keys ?? config.keys @@ -213,11 +231,13 @@ exports.init = function initDB(peer, config) { if (!opts.type) return cb(new Error('create() requires a `type`')) // Create full opts: + const tangles = populateTangles(opts.tangles ?? []) let tempMsg try { tempMsg = FeedV1.create({ when: Date.now(), ...opts, + tangles, existing: [], keys, }) @@ -226,7 +246,7 @@ exports.init = function initDB(peer, config) { } const feedId = FeedV1.getFeedId(tempMsg) const existing = msgsPerFeed.getAll(feedId) - const fullOpts = { when: Date.now(), ...opts, existing, keys } + const fullOpts = { when: Date.now(), ...opts, tangles, existing, keys } // If opts ask for encryption, encrypt and put ciphertext in opts.content const recps = fullOpts.content.recps diff --git a/test/create.test.js b/test/create.test.js index 82a863f..73fc1c0 100644 --- a/test/create.test.js +++ b/test/create.test.js @@ -12,6 +12,7 @@ const DIR = path.join(os.tmpdir(), 'ppppp-db-create') rimraf.sync(DIR) const keys = generateKeypair('alice') +const bobKeys = generateKeypair('bob') let peer test('setup', async (t) => { peer = SecretStack({ appKey: caps.shs }) @@ -79,6 +80,27 @@ test('create() encrypted with box', async (t) => { t.equals(msgDecrypted.content.text, 'I am chewing food') }) +test('create() with tangles', async (t) => { + const recA = await p(peer.db.create)({ + type: 'comment', + content: { text: 'I am root' }, + }) + t.equal(recA.msg.content.text, 'I am root', 'root text correct') + + const recB = await p(peer.db.create)({ + type: 'comment', + content: { text: 'I am comment 1' }, + tangles: [recA.hash], + keys: bobKeys, + }) + t.equal(recB.msg.metadata.tangles[recA.hash].depth, 1, 'tangle depth 1') + t.deepEquals( + recB.msg.metadata.tangles[recA.hash].prev, + [recA.hash], + 'tangle prev' + ) +}) + test('teardown', (t) => { peer.close(t.end) })