assai 2.1.1 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,5 +2,8 @@
2
2
  * ```
3
3
  * "_id" -> "id"
4
4
  * ```
5
+ * Recursively renames all `_id` keys to `id` in objects and arrays.
6
+ * Does not mutate the original input.
7
+ * @param {*} obj
5
8
  */
6
9
  export function renameToDevId(obj: any): any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "assai",
3
- "version": "2.1.1",
3
+ "version": "2.1.2",
4
4
  "repository": {
5
5
  "url": "https://github.com/TimeLord2010/assai",
6
6
  "type": "git"
@@ -2,14 +2,35 @@
2
2
  * ```
3
3
  * "_id" -> "id"
4
4
  * ```
5
+ * Recursively renames all `_id` keys to `id` in objects and arrays.
6
+ * Does not mutate the original input.
7
+ * @param {*} obj
5
8
  */
6
9
  export function renameToDevId(obj) {
7
- if (!obj) return obj
8
- let { _id, ...rest } = obj
9
- if (_id === undefined) return obj
10
- if (_id === null) return rest
11
- return {
12
- id: _id,
13
- ...rest
10
+ if (obj == null) return obj
11
+ if (typeof obj !== 'object') return obj
12
+ if (obj instanceof Date) return obj
13
+
14
+ if (Array.isArray(obj)) {
15
+ let hasChanges = false
16
+ const transformed = new Array(obj.length)
17
+ for (let i = 0; i < obj.length; i++) {
18
+ const item = obj[i]
19
+ const transformedItem = renameToDevId(item)
20
+ transformed[i] = transformedItem
21
+ if (transformedItem !== item) hasChanges = true
22
+ }
23
+ return hasChanges ? transformed : obj
14
24
  }
25
+
26
+ let hasChanges = false
27
+ /** @type {Record<string, any>} */
28
+ const transformed = {}
29
+ for (const [key, value] of Object.entries(obj)) {
30
+ const newKey = key === '_id' ? 'id' : key
31
+ const newValue = renameToDevId(value)
32
+ transformed[newKey] = newValue
33
+ if (newKey !== key || newValue !== value) hasChanges = true
34
+ }
35
+ return hasChanges ? transformed : obj
15
36
  }
@@ -24,6 +24,7 @@ export function renameToMongoId(obj) {
24
24
  }
25
25
 
26
26
  let hasChanges = false
27
+ /** @type {Record<string, any>} */
27
28
  const transformed = {}
28
29
  for (const [key, value] of Object.entries(obj)) {
29
30
  const newKey = key === 'id' ? '_id' : key