mirror of https://codeberg.org/pzp/pzp-db.git
add() supports inferring tangleID
This commit is contained in:
parent
fa15271fdf
commit
42acbc310f
25
lib/index.js
25
lib/index.js
|
@ -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 }))
|
||||
|
|
|
@ -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)()
|
||||
|
|
Loading…
Reference in New Issue