Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Improve calculateChangeHash to avoid circular reference errors #403

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 34 additions & 4 deletions libraries/botbuilder-core/src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/
import { TurnContext } from './turnContext';
import { Assertion, assert } from 'botbuilder-stdlib';
import { createHash } from 'crypto';

/**
* Callback to calculate a storage key.
Expand Down Expand Up @@ -115,10 +116,39 @@ export const assertStoreItems: Assertion<StoreItems> = (val, path) => {
* @param item Item to calculate the change hash for.
*/
export function calculateChangeHash(item: StoreItem): string {
const cpy: any = { ...item };
if (cpy.eTag) {
delete cpy.eTag;
let result = '';
if (!item) {
return result;
}

return JSON.stringify(cpy);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { eTag, ...rest } = item;
ceciliaavila marked this conversation as resolved.
Show resolved Hide resolved

try {
result = JSON.stringify(rest);
} catch (error) {
if (!error?.message.includes('circular structure')) {
throw error;
}

const seen = new WeakMap();
result = JSON.stringify(rest, function circularReplacer(key, value) {
if (value === null || value === undefined || typeof value !== 'object') {
return value;
}

const path = seen.get(value);
if (path) {
return `[Circular *${path.join('.')}]`;
}

const parent = seen.get(this) ?? [];
seen.set(value, [...parent, key]);
return value;
});
}

const hash = createHash('sha256', { encoding: 'utf-8' });
const hashed = hash.update(result).digest('hex');
return hashed;
}
Loading