Skip to content
Merged
Show file tree
Hide file tree
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
34 changes: 26 additions & 8 deletions src/entity/in_memory.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import lodash from "lodash";

// import { ESSE } from "@exabyte-io/esse.js";
import { deepClone } from "../utils/clone";
import { clone, deepClone } from "../utils/clone";
import { getSchemaByClassName } from "../utils/schemas";

// TODO: https://exabyte.atlassian.net/browse/SOF-5946
Expand All @@ -12,8 +12,11 @@ export class InMemoryEntity {
return new this.prototype.constructor(config);
}

constructor(config) {
this._json = deepClone(config || {});
// Override if config deepClone is needed
static _isDeepCloneRequired = false;

constructor(config = {}) {
this._json = this.constructor._isDeepCloneRequired ? deepClone(config) : clone(config);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd add explicitly a static var: static _isDeepCloneRequired = false

}

/**
Expand Down Expand Up @@ -46,11 +49,24 @@ export class InMemoryEntity {

/**
* @summary Array of fields to exclude from resulted JSON
* @param exclude {String[]}
* @param {String[]} exclude
*/
toJSON(exclude = []) {
const config = deepClone(lodash.omit(this._json, exclude));
return this.clean(config);
return this.constructor._isDeepCloneRequired
? this.toJSONSafe(exclude)
: this.toJSONQuick(exclude);
}

toJSONSafe(exclude = []) {
const config = lodash.omit(this._json, exclude);

return this.clean(deepClone(config));
}

toJSONQuick(exclude = []) {
const config = lodash.omit(this._json, exclude);

return this.clean(clone(config));
}

/**
Expand Down Expand Up @@ -90,10 +106,12 @@ export class InMemoryEntity {

isValid() {
const ctx = this.schema.newContext();
ctx.validate(this.toJSON());
const json = this.toJSON();

ctx.validate(json);

if (!ctx.isValid()) {
console.log(JSON.stringify(this.toJSON()));
console.log(JSON.stringify(json));
if (ctx.getErrorObject) {
console.log(ctx.getErrorObject());
}
Expand Down
4 changes: 4 additions & 0 deletions src/utils/clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@
export function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}

export function clone(obj) {
return { ...obj };
}