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

fix: use own object flattening function that supports class objects #402

Merged
merged 6 commits into from
Feb 5, 2025
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
5 changes: 0 additions & 5 deletions packages/moleculer-db/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/moleculer-db/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
},
"dependencies": {
"@seald-io/nedb": "^3.0.0",
"flat": "^5.0.2",
"lodash": "^4.17.21"
}
}
6 changes: 2 additions & 4 deletions packages/moleculer-db/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@
"use strict";

const _ = require("lodash");
const { flatten } = require("flat");
const { MoleculerClientError, ValidationError } = require("moleculer").Errors;
const { EntityNotFoundError } = require("./errors");
const MemoryAdapter = require("./memory-adapter");
const pkg = require("../package.json");
const util = require("util");
const { copyFieldValueByPath } = require("./utils");
const { copyFieldValueByPath, flatten } = require("./utils");
const stringToPath = require("lodash/_stringToPath");

/**
Expand Down Expand Up @@ -1028,7 +1026,7 @@ module.exports = {
});

if (this.settings.useDotNotation)
sets = flatten(sets, { safe: true });
sets = flatten(sets);

return sets;
})
Expand Down
58 changes: 58 additions & 0 deletions packages/moleculer-db/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,61 @@ function copyFieldValueByPath(doc, paths, res, pathIndex = 0, cachePaths = []) {
}

exports.copyFieldValueByPath = copyFieldValueByPath;

/**
* Flattens a JavaScript object using dot notation while preserving arrays and non-plain objects
* @param {Object} obj - The object to flatten
* @param {String} [prefix=""] - The prefix to use for nested keys (used internally for recursion)
* @returns {Object} A flattened object with dot notation keys
*
* @example
* const input = {
* name: "John",
* address: {
* street: "Main St",
* location: {
* city: "Boston",
* country: "USA"
* }
* },
* account: {
* createdAt: new Date("2024-01-01"),
* settings: {
* theme: null,
* language: undefined
* }
* },
* scores: [85, 90, 95],
* _id: ObjectId("507f1f77bcf86cd799439011")
* };
*
* // Returns:
* // {
* // "name": "John",
* // "address.street": "Main St",
* // "address.location.city": "Boston",
* // "address.location.country": "USA",
* // "account.createdAt": Date("2024-01-01T00:00:00.000Z"),
* // "account.settings.theme": null,
* // "account.settings.language": undefined,
* // "scores": [85, 90, 95],
* // "_id": ObjectId("507f1f77bcf86cd799439011")
* // }
*/
function flatten(obj, prefix = "") {
return Object.keys(obj).reduce((acc, key) => {
const prefixedKey = prefix ? `${prefix}.${key}` : key;
const value = obj[key];

// Check if value is a plain object (not array, not null, and constructor is Object)
const isPlainObject = typeof value === "object" && value && value.constructor === Object;

// If it's a plain object, flatten it recursively
// Otherwise, keep the value as is (handles primitives, null, undefined, arrays, dates, ObjectId, etc.)
return isPlainObject
? { ...acc, ...flatten(value, prefixedKey) }
: { ...acc, [prefixedKey]: value };
}, {});
}

exports.flatten = flatten;
66 changes: 66 additions & 0 deletions packages/moleculer-db/test/unit/utils.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"use strict";

const { flatten } = require("../../src/utils");

class ObjectId {
constructor() {
this.timestamp = Math.floor(Date.now() / 1000).toString(16).padStart(8, "0");
this.machineId = Math.floor(Math.random() * 16777216).toString(16).padStart(6, "0");
this.processId = Math.floor(Math.random() * 65536).toString(16).padStart(4, "0");
this.counter = Math.floor(Math.random() * 16777216).toString(16).padStart(6, "0");
}

toString() {
return this.timestamp + this.machineId + this.processId + this.counter;
}

getTimestamp() {
return new Date(parseInt(this.timestamp, 16) * 1000);
}
}

describe("Test Utils", () => {
describe("flatten", () => {
it("should properly flatten a given object", () => {
const oid = new ObjectId();
const date = new Date("2024-01-01");
const obj = {
name: "John",
active: true,
address: {
street: "Main St",
location: {
city: "Boston",
country: "USA"
}
},
account: {
createdAt: date,
identifier: oid,
isSync: false,
settings: {
theme: null,
language: undefined
}
},
scores: [85, 90, 95],
};

const expected = {
"name": "John",
"active": true,
"address.street": "Main St",
"address.location.city": "Boston",
"address.location.country": "USA",
"account.createdAt": date,
"account.identifier": oid,
"account.settings.theme": null,
"account.settings.language": undefined,
"account.isSync": false,
"scores": [85, 90, 95],
};

expect(flatten(obj)).toEqual(expected);
});
});
});