add() supports inferring tangleID

This commit is contained in:
Andre Staltz 2023-12-15 15:49:54 +02:00
parent fa15271fdf
commit 42acbc310f
No known key found for this signature in database
GPG Key ID: 9EDE23EA7E8A4890
2 changed files with 25 additions and 2 deletions

View File

@ -451,9 +451,30 @@ function initDB(peer, config) {
return null
}
/**
* @param {Pick<RecPresent, 'id' | 'msg'>} rec
* @returns {MsgID}
*/
function inferTangleID(rec) {
if (MsgV3.isRoot(rec.msg)) return rec.id
let tangleID = /**@type {string | null}*/ (null)
for (const id in rec.msg.metadata.tangles) {
if (tangleID) {
// prettier-ignore
throw new Error('Cannot infer tangleID in msg because it has more than one tangle', { cause: JSON.stringify(rec.msg) })
} else {
tangleID = id
}
}
if (!tangleID) {
throw new Error('Cannot infer tangleID in msg because it has no tangles')
}
return tangleID
}
/**
* @param {Msg} msg
* @param {MsgID} tangleID
* @param {MsgID | null} tangleID
* @param {CB<RecPresent>} cb
*/
function add(msg, tangleID, cb) {
@ -465,6 +486,8 @@ function initDB(peer, config) {
if ((rec = getRecord(msgID))) return cb(null, rec)
else rec = { msg, id: msgID }
tangleID ??= inferTangleID(rec)
let err
if ((err = verifyRec(rec, tangleID))) {
return cb(new Error('add() failed to verify msg', { cause: err }))

View File

@ -45,7 +45,7 @@ test('add()', async (t) => {
},
})
const rec = await p(peer.db.add)(inputMsg, rootID)
const rec = await p(peer.db.add)(inputMsg, null) // tangleID implicit
assert.equal(rec.msg.data.text, 'This is the first post!')
const stats = await p(peer.db.log.stats)()