Skip to content

Commit

Permalink
Fix up and test cache.createId().
Browse files Browse the repository at this point in the history
  • Loading branch information
dlongley committed Nov 17, 2024
1 parent 6b85e84 commit 246532f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
16 changes: 8 additions & 8 deletions lib/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,20 +74,20 @@ bedrock.events.on('bedrock-mongodb.ready', async () => {
});

/**
* Creates a cache entry ID from a document. This utility function is useful
* for applications that want to generate cache entries for JSON documents
* without storing the documents in the cache.
* Creates a cache entry ID from an object. This utility function is useful
* for applications that want to generate cache entries for JSON objects
* without storing the objects in the cache.
*
* @param {object} options - Options to use.
* @param {object} [options.document] - The document to generate an ID from.
* @param {object} [options.object] - The object to generate an ID from.
*
* @returns {Promise<object>} Resolves to an object with `id`.
*/
export async function createId({document} = {}) {
assert.object(document, 'document');
export async function createId({object} = {}) {
assert.object(object, 'object');

// canonicalize document to a string
const string = canonicalize(document);
// canonicalize object to a string
const string = canonicalize(object);
// hash string
const digest = await _sha256({string});
// express digest as multibase-multihash string
Expand Down
21 changes: 21 additions & 0 deletions test/mocha/10-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,27 @@ import crypto from 'node:crypto';
import {tokenizers} from '@bedrock/tokenizer';

describe('Cache', function() {
describe('cache.createId()', () => {
it('should create the ID for equivalent objects', async () => {
const object1 = {
a: 'a',
b: 'b',
c: 'c',
num: 1,
bool: true
};
const object2 = {...object1};
const object3 = {...object1, a: 'different'};

const {id: id1} = await cache.createId({object: object1});
const {id: id2} = await cache.createId({object: object2});
const {id: id3} = await cache.createId({object: object3});

id1.should.equal(id2);
id1.should.not.equal(id3);
});
});

describe('cache.upsert()', () => {
it('should insert and get a cache entry', async () => {
const id = crypto.randomUUID();
Expand Down

0 comments on commit 246532f

Please sign in to comment.