object-reshaper
Advanced tools
Comparing version 0.2.0 to 0.3.0
# Changelog | ||
## [0.3.0](https://github.com/dextertanyj/object-reshaper/compare/v0.2.0...v0.3.0) (2023-05-07) | ||
### ⚠ BREAKING CHANGES | ||
* improve null and undefined handling | ||
### Features | ||
* implement support for multidimensional arrays ([5a7dced](https://github.com/dextertanyj/object-reshaper/commit/5a7dceda4dd9918428d2c453c4c797ab0c5a4f66)) | ||
* improve null and undefined handling ([9607dcd](https://github.com/dextertanyj/object-reshaper/commit/9607dcd64111ddadcddac852a51858c120905e41)) | ||
* improve support for union input types ([a9ab9b3](https://github.com/dextertanyj/object-reshaper/commit/a9ab9b3d4635a02a5a16a1deaab9202680dffcd5)) | ||
### Bug Fixes | ||
* isolate nested array element types to prevent path pollution ([9c4acd0](https://github.com/dextertanyj/object-reshaper/commit/9c4acd0bcb58b3b7bad34e1a6878ede68d162d33)) | ||
## [0.2.0](https://github.com/dextertanyj/object-reshaper/compare/v0.1.0...v0.2.0) (2023-04-26) | ||
@@ -4,0 +22,0 @@ |
@@ -0,3 +1,4 @@ | ||
import { Schema } from "./types/schema"; | ||
import { Transformed } from "./types/transformed"; | ||
import { reshaperBuilder } from "./reshape"; | ||
import { Schema, Transformed } from "./types"; | ||
export { reshaperBuilder, Schema, Transformed }; |
@@ -1,2 +0,3 @@ | ||
import { Reshaper, Schema } from "./types"; | ||
export declare const reshaperBuilder: <T, S extends Schema<T>>(schema: S) => Reshaper<T, S>; | ||
import { Reshaper } from "./types/core"; | ||
import { Schema } from "./types/schema"; | ||
export declare const reshaperBuilder: <T extends Record<string, unknown>, S extends Schema<T>>(schema: S) => Reshaper<T, S>; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.reshaperBuilder = void 0; | ||
const isDeclaredArrayTemplate = (template) => { | ||
return Array.isArray(template) && template.length === 2 && typeof template[0] === "string"; | ||
}; | ||
function splitPath(path) { | ||
return path.split(/\.|(\[\*\])|(\[\d+\])/g).filter((item) => item !== undefined && item !== ""); | ||
} | ||
const readField = (o, field) => { | ||
if (typeof o !== "object") { | ||
if (typeof o !== "object" || o === null) { | ||
return undefined; | ||
} | ||
if (o === null) { | ||
return o; | ||
} | ||
if (!Object.prototype.hasOwnProperty.call(o, field)) { | ||
@@ -16,22 +19,15 @@ return undefined; | ||
}; | ||
const handleArrayAccess = (field, fieldName, path) => { | ||
const arrayAccessor = fieldName.split("["); | ||
const arrayName = arrayAccessor[0]; | ||
const arrayIndex = arrayAccessor[1].split("]")[0]; | ||
const array = readField(field, arrayName); | ||
if (array === undefined || array === null) { | ||
return array; | ||
} | ||
if (!Array.isArray(array)) { | ||
const handleArrayAccess = (array, index, path) => { | ||
if (array === undefined || array === null || !Array.isArray(array)) { | ||
return undefined; | ||
} | ||
if (arrayIndex === "*") { | ||
if (index === "[*]") { | ||
const result = handleFlattenedArrayAccess(array, [...path]); | ||
if (path.find((item) => item.endsWith("[*]"))) { | ||
return result.flatMap((item) => item === undefined || item === null ? [] : item); | ||
if (path.find((item) => item === "[*]")) { | ||
return result.flatMap((item) => (item === undefined ? [] : item)); | ||
} | ||
return result; | ||
return result.filter((item) => item !== undefined); | ||
} | ||
else { | ||
return handleIndexedArrayAccess(array, parseInt(arrayIndex), [...path]); | ||
return handleIndexedArrayAccess(array, parseInt(index.slice(1, -1)), path); | ||
} | ||
@@ -43,9 +39,12 @@ }; | ||
} | ||
const result = fieldAccessor(array[index], [...path]); | ||
const result = fieldAccessor(array[index], path); | ||
return result; | ||
}; | ||
const handleFlattenedArrayAccess = (array, path) => { | ||
return array | ||
if (path.length === 0) { | ||
return array.filter((item) => item !== undefined); | ||
} | ||
return (array | ||
.filter((item) => item !== undefined && item !== null) | ||
.map((item) => fieldAccessor(item, [...path])); | ||
.map((item) => fieldAccessor(item, [...path]))); | ||
}; | ||
@@ -55,3 +54,3 @@ const fieldAccessor = (data, path) => { | ||
for (let fieldName = path.shift(); fieldName !== undefined && field !== undefined; fieldName = path.shift()) { | ||
if (fieldName.endsWith("]")) { | ||
if (fieldName.match(/(\[\d+\])|(\[\*\])/g)) { | ||
return handleArrayAccess(field, fieldName, [...path]); | ||
@@ -65,2 +64,24 @@ } | ||
}; | ||
const arrayConstructor = (data, template) => { | ||
const path = template[0]; | ||
const array = fieldAccessor(data, splitPath(path)); | ||
if (!Array.isArray(array)) { | ||
return undefined; | ||
} | ||
const schema = template[1]; | ||
if (typeof schema === "string") { | ||
return array | ||
.map((item) => fieldAccessor(item, splitPath(schema))) | ||
.filter((item) => item !== undefined); | ||
} | ||
if (typeof schema !== "object" || schema === null) { | ||
return undefined; | ||
} | ||
if (isDeclaredArrayTemplate(schema)) { | ||
return array.map((item) => arrayConstructor(item, schema)).filter((item) => item !== undefined); | ||
} | ||
return array | ||
.map((item) => objectConstructor(item, schema)) | ||
.filter((item) => item !== undefined); | ||
}; | ||
const objectConstructor = (data, schema) => { | ||
@@ -71,3 +92,3 @@ const result = {}; | ||
if (typeof item === "string") { | ||
result[key] = fieldAccessor(data, item.split(".")); | ||
result[key] = fieldAccessor(data, splitPath(item)); | ||
} | ||
@@ -77,17 +98,4 @@ else if (typeof item === "object" && !Array.isArray(item)) { | ||
} | ||
else { | ||
const fieldName = item[0]; | ||
const subSchema = item[1]; | ||
const array = fieldAccessor(data, fieldName.split(".")); | ||
if (!Array.isArray(array)) { | ||
result[key] = undefined; | ||
} | ||
else { | ||
result[key] = array.map((item) => { | ||
if (typeof item !== "object") { | ||
return undefined; | ||
} | ||
return objectConstructor(item, subSchema); | ||
}); | ||
} | ||
else if (isDeclaredArrayTemplate(item)) { | ||
result[key] = arrayConstructor(data, item); | ||
} | ||
@@ -94,0 +102,0 @@ } |
@@ -0,3 +1,4 @@ | ||
import { Schema } from "./types/schema"; | ||
import { Transformed } from "./types/transformed"; | ||
import { reshaperBuilder } from "./reshape"; | ||
import { Schema, Transformed } from "./types"; | ||
export { reshaperBuilder, Schema, Transformed }; |
@@ -1,2 +0,3 @@ | ||
import { Reshaper, Schema } from "./types"; | ||
export declare const reshaperBuilder: <T, S extends Schema<T>>(schema: S) => Reshaper<T, S>; | ||
import { Reshaper } from "./types/core"; | ||
import { Schema } from "./types/schema"; | ||
export declare const reshaperBuilder: <T extends Record<string, unknown>, S extends Schema<T>>(schema: S) => Reshaper<T, S>; |
@@ -0,8 +1,11 @@ | ||
const isDeclaredArrayTemplate = (template) => { | ||
return Array.isArray(template) && template.length === 2 && typeof template[0] === "string"; | ||
}; | ||
function splitPath(path) { | ||
return path.split(/\.|(\[\*\])|(\[\d+\])/g).filter((item) => item !== undefined && item !== ""); | ||
} | ||
const readField = (o, field) => { | ||
if (typeof o !== "object") { | ||
if (typeof o !== "object" || o === null) { | ||
return undefined; | ||
} | ||
if (o === null) { | ||
return o; | ||
} | ||
if (!Object.prototype.hasOwnProperty.call(o, field)) { | ||
@@ -13,22 +16,15 @@ return undefined; | ||
}; | ||
const handleArrayAccess = (field, fieldName, path) => { | ||
const arrayAccessor = fieldName.split("["); | ||
const arrayName = arrayAccessor[0]; | ||
const arrayIndex = arrayAccessor[1].split("]")[0]; | ||
const array = readField(field, arrayName); | ||
if (array === undefined || array === null) { | ||
return array; | ||
} | ||
if (!Array.isArray(array)) { | ||
const handleArrayAccess = (array, index, path) => { | ||
if (array === undefined || array === null || !Array.isArray(array)) { | ||
return undefined; | ||
} | ||
if (arrayIndex === "*") { | ||
if (index === "[*]") { | ||
const result = handleFlattenedArrayAccess(array, [...path]); | ||
if (path.find((item) => item.endsWith("[*]"))) { | ||
return result.flatMap((item) => item === undefined || item === null ? [] : item); | ||
if (path.find((item) => item === "[*]")) { | ||
return result.flatMap((item) => (item === undefined ? [] : item)); | ||
} | ||
return result; | ||
return result.filter((item) => item !== undefined); | ||
} | ||
else { | ||
return handleIndexedArrayAccess(array, parseInt(arrayIndex), [...path]); | ||
return handleIndexedArrayAccess(array, parseInt(index.slice(1, -1)), path); | ||
} | ||
@@ -40,9 +36,12 @@ }; | ||
} | ||
const result = fieldAccessor(array[index], [...path]); | ||
const result = fieldAccessor(array[index], path); | ||
return result; | ||
}; | ||
const handleFlattenedArrayAccess = (array, path) => { | ||
return array | ||
if (path.length === 0) { | ||
return array.filter((item) => item !== undefined); | ||
} | ||
return (array | ||
.filter((item) => item !== undefined && item !== null) | ||
.map((item) => fieldAccessor(item, [...path])); | ||
.map((item) => fieldAccessor(item, [...path]))); | ||
}; | ||
@@ -52,3 +51,3 @@ const fieldAccessor = (data, path) => { | ||
for (let fieldName = path.shift(); fieldName !== undefined && field !== undefined; fieldName = path.shift()) { | ||
if (fieldName.endsWith("]")) { | ||
if (fieldName.match(/(\[\d+\])|(\[\*\])/g)) { | ||
return handleArrayAccess(field, fieldName, [...path]); | ||
@@ -62,2 +61,24 @@ } | ||
}; | ||
const arrayConstructor = (data, template) => { | ||
const path = template[0]; | ||
const array = fieldAccessor(data, splitPath(path)); | ||
if (!Array.isArray(array)) { | ||
return undefined; | ||
} | ||
const schema = template[1]; | ||
if (typeof schema === "string") { | ||
return array | ||
.map((item) => fieldAccessor(item, splitPath(schema))) | ||
.filter((item) => item !== undefined); | ||
} | ||
if (typeof schema !== "object" || schema === null) { | ||
return undefined; | ||
} | ||
if (isDeclaredArrayTemplate(schema)) { | ||
return array.map((item) => arrayConstructor(item, schema)).filter((item) => item !== undefined); | ||
} | ||
return array | ||
.map((item) => objectConstructor(item, schema)) | ||
.filter((item) => item !== undefined); | ||
}; | ||
const objectConstructor = (data, schema) => { | ||
@@ -68,3 +89,3 @@ const result = {}; | ||
if (typeof item === "string") { | ||
result[key] = fieldAccessor(data, item.split(".")); | ||
result[key] = fieldAccessor(data, splitPath(item)); | ||
} | ||
@@ -74,17 +95,4 @@ else if (typeof item === "object" && !Array.isArray(item)) { | ||
} | ||
else { | ||
const fieldName = item[0]; | ||
const subSchema = item[1]; | ||
const array = fieldAccessor(data, fieldName.split(".")); | ||
if (!Array.isArray(array)) { | ||
result[key] = undefined; | ||
} | ||
else { | ||
result[key] = array.map((item) => { | ||
if (typeof item !== "object") { | ||
return undefined; | ||
} | ||
return objectConstructor(item, subSchema); | ||
}); | ||
} | ||
else if (isDeclaredArrayTemplate(item)) { | ||
result[key] = arrayConstructor(data, item); | ||
} | ||
@@ -91,0 +99,0 @@ } |
@@ -0,4 +1,5 @@ | ||
import { Schema } from "./types/schema"; | ||
import { Transformed } from "./types/transformed"; | ||
import { reshaperBuilder } from "./reshape"; | ||
import { Schema, Transformed } from "./types"; | ||
export { reshaperBuilder, Schema, Transformed }; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,3 +0,4 @@ | ||
import { Reshaper, Schema } from "./types"; | ||
export declare const reshaperBuilder: <T, S extends Schema<T>>(schema: S) => Reshaper<T, S>; | ||
import { Reshaper } from "./types/core"; | ||
import { Schema } from "./types/schema"; | ||
export declare const reshaperBuilder: <T extends Record<string, unknown>, S extends Schema<T>>(schema: S) => Reshaper<T, S>; | ||
//# sourceMappingURL=reshape.d.ts.map |
{ | ||
"name": "object-reshaper", | ||
"version": "0.2.0", | ||
"version": "0.3.0", | ||
"description": "TypeScript-first schema-based object transformation", | ||
@@ -31,7 +31,13 @@ "license": "MIT", | ||
"typescript", | ||
"schema", | ||
"type", | ||
"object", | ||
"mapper", | ||
"mapping", | ||
"transform" | ||
"transform", | ||
"transformer", | ||
"convert", | ||
"shape", | ||
"type", | ||
"schema", | ||
"path", | ||
"dto" | ||
], | ||
@@ -85,3 +91,2 @@ "scripts": { | ||
], | ||
"rootDir": "src", | ||
"testRegex": ".*\\.spec\\.ts$", | ||
@@ -92,6 +97,10 @@ "transform": { | ||
"collectCoverageFrom": [ | ||
"**/*.(t|j)s" | ||
"src/**/*.(t|j)s" | ||
], | ||
"coverageDirectory": "../coverage", | ||
"testEnvironment": "node" | ||
"coverageDirectory": "./coverage", | ||
"testEnvironment": "node", | ||
"moduleNameMapper": { | ||
"^@$": "<rootDir>/src", | ||
"^@/(.*)$": "<rootDir>/src/$1" | ||
} | ||
}, | ||
@@ -98,0 +107,0 @@ "lint-staged": { |
437
README.md
@@ -9,5 +9,18 @@ # Object Reshaper | ||
## Table of Contents | ||
- [Introduction](#introduction) | ||
- [Installation](#installation) | ||
- [Requirements](#requirements) | ||
- [Usage](#usage) | ||
- [Property Access](#property-access) | ||
- [Declaring Multidimensional or Nested Arrays](#declaring-multidimensional-or-nested-arrays) | ||
- [Examples](#examples) | ||
- [Specification](#specification) | ||
- [`undefined` & `null` Inputs](#undefined--null-inputs) | ||
- [Union Input Types (Experimental)](#union-input-types-experimental) | ||
## Introduction | ||
Object Reshaper provides a type safe interface for transforming objects using a schema, allowing users to easily transform objects without having to write boilerplate code. | ||
Object Reshaper provides a type-safe interface for transforming objects using a schema, allowing users to easily transform objects without having to write boilerplate code. | ||
It supports renaming fields, extracting nested objects, and flattening nested arrays. | ||
@@ -19,3 +32,3 @@ Simply define a schema that describes the desired output using dot notation and Object Reshaper will generate a function that transforms input objects into the desired shape. | ||
> Object Reshaper is not a replacement for existing object validation libraries. | ||
> In fact, it is strongly recommended that any inputs from users or external sources be validated before being passed to Object Reshaper. | ||
> It is strongly recommended that any inputs from users or external sources be validated before being passed to Object Reshaper. | ||
> Object Reshaper does not perform any validation of object properties at runtime and supplying any inputs that do not conform to the expected type will result in undefined behaviour. | ||
@@ -25,2 +38,6 @@ | ||
```sh | ||
$ npm install object-reshaper | ||
``` | ||
### Requirements | ||
@@ -30,8 +47,373 @@ | ||
```sh | ||
$ npm install object-reshaper | ||
## Usage | ||
Object Reshaper provides a `reshaperBuilder` function that takes in a schema and returns a function that transforms input objects into the desired shape. | ||
The schema is a JavaScript object that should have the same structure as the desired output object, including any nested structures. | ||
The values of each property should be a string that describes the path to the desired property in the input object. | ||
```ts | ||
import { reshaperBuilder, Schema } from "object-reshaper"; | ||
type Input = { | ||
id: number; | ||
name: string; | ||
}; | ||
const schema = { | ||
uin: "id", | ||
username: "name", | ||
} as const satisfies Schema<Input>; | ||
const reshaper = reshaperBuilder<Input, typeof schema>(schema); | ||
reshaper({ id: 1, name: "John" }); // => { uin: 1, username: "John" } (Type: { uin: number, username: string }) | ||
``` | ||
## Basic Usage | ||
> To provide type safety, schemas must be declared with a `const` assertion so that TypeScript can retrieve the type of each property being accessed.<br> | ||
> Optionally, the `satisfies` operator can be used to ensure that the schema is valid for the input type during declaration. | ||
### Property Access | ||
Properties in nested objects can be accessed using dot notation and elements in arrays can be accessed using the `[*]` operator. | ||
The `[*]` operator, when chained with a dot and a property name, returns an array containing the value of the property for each element in the array. | ||
The `[*]` operator also automatically flattens the result of chained `[*]` operators. | ||
Object Reshaper also supports accessing single elements within arrays by referencing their index. | ||
```ts | ||
type User = { | ||
id: number; | ||
name: { | ||
first: string; | ||
last?: string; | ||
}; | ||
contact: number[]; | ||
posts: { | ||
title: string; | ||
tags: string[]; | ||
}[]; | ||
}; | ||
const user: User = { | ||
id: 1, | ||
name: { | ||
first: "John", | ||
}, | ||
contact: [12345678], | ||
posts: [ | ||
{ title: "Hello World", tags: ["hello", "world"] }, | ||
{ title: "My Second Post", tags: ["diary"] }, | ||
], | ||
}; | ||
``` | ||
<table> | ||
<tr> | ||
<th>Path</th> | ||
<th>Type</th> | ||
<th>Value</th> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
id | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
number | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
1 | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
name | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
{ | ||
first: string; | ||
last?: string; | ||
} | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
{ first: "John" } | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
name.first | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
string | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
"John" | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
name.last | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
string | undefined | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
undefined | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
contact or contact[*] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
number[] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
[12345678] | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
contact[0] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
number | undefined | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
12345678 | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
contact[1] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
number | undefined | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
undefined | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
posts or posts[*] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
{ | ||
title: string; | ||
tags: string[]; | ||
}[] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
[ | ||
{ | ||
title: "Hello World", | ||
tags: ["hello", "world"], | ||
}, | ||
{ | ||
title: "My Second Post", | ||
tags: ["diary"], | ||
}, | ||
] | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
posts[*].title | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
string[] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
["Hello World", "My Second Post"] | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
posts[*].tags | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
string[][] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
[["hello", "world"], ["diary"]] | ||
``` | ||
</td> | ||
</tr> | ||
<tr> | ||
<td> | ||
```ts | ||
posts[*].tags[*] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
string[] | ||
``` | ||
</td> | ||
<td> | ||
```ts | ||
["hello", "world", "diary"] | ||
``` | ||
</td> | ||
</tr> | ||
</table> | ||
_\*The above list is not exhaustive._ | ||
### Declaring Multidimensional or Nested Arrays | ||
Object Reshaper also supports the creation of multidimensional or nested arrays using a 2-tuple syntax, `[<path>, <element definition>]`. | ||
- The first element of the 2-tuple must be a path to the array containing elements to be iterated. _(Chained `[*]` operators are supported.)_ | ||
- The second element of the 2-tuple contains the definition of the elements in the array. | ||
- The second element may either be a path, a 2-tuple, or an object. | ||
- Paths within the element definition are relative to the array element being iterated. | ||
```ts | ||
const schema = { | ||
posts: ["posts[*]", { title: "title", category: "tags[0]" }], | ||
} as const satisfies Schema<User>; | ||
const reshaper = reshaperBuilder<User, typeof schema>(schema); | ||
reshaper(user); | ||
// => { | ||
// posts: [ | ||
// { title: "Hello World", category: "hello" }, | ||
// { title: "My Second Post", category: "diary" }, | ||
// ], | ||
// } | ||
``` | ||
## Examples | ||
### Basic Usage | ||
Renaming property names | ||
@@ -71,3 +453,3 @@ | ||
## Manipulating Arrays | ||
### Manipulating Arrays | ||
@@ -122,6 +504,4 @@ Accessing array elements | ||
_Support for multidimensional arrays coming soon_ | ||
### Transforming Objects Within Arrays | ||
## Transforming Objects Within Arrays | ||
Flatten nested arrays and transform elements | ||
@@ -148,6 +528,3 @@ | ||
{ | ||
nested: [ | ||
{ item: { id: 2, name: "second" } }, | ||
{ item: { id: 3, name: "third" } }, | ||
], | ||
nested: [{ item: { id: 2, name: "second" } }, { item: { id: 3, name: "third" } }], | ||
}, | ||
@@ -157,1 +534,35 @@ ], | ||
``` | ||
## Specification | ||
### `undefined` & `null` Inputs | ||
Object Reshaper supports `undefined` or `null` inputs and follows the same behaviour as the optional-chaining operator, `?.`, in JavaScript. | ||
When using the `[*]` operator, `undefined` values are removed from the resulting array. | ||
### Union Input Types (Experimental) | ||
Object Reshaper has experimental support for input types that contain union types. | ||
The current implementation supports most union types but has known limitations when dealing with arrays. | ||
In particular, arrays containing objects of different types cannot be perfectly distinguished from each other at runtime, | ||
resulting in an empty array always being returned, rather than `undefined`. | ||
For example, the two different possible types of the `array` property cannot be distinguished at runtime since Object Reshaper | ||
does not record the type of the input object for use during runtime. As a result, Object Reshaper cannot determine if the object | ||
in the array is of type `{ id: number; a?: number }` or `{ id: number; b?: string }`, since both need not contain `a`. | ||
```ts | ||
type Input = { | ||
array: { id: number; a?: number }[] | { id: number; b?: string }[]; | ||
}; | ||
const schema = { | ||
new: "array[*].a", | ||
} as const satisfies Schema<Input>; | ||
const reshaper = reshaperBuilder<Input, typeof schema>(schema); | ||
reshaper({ array: [{ id: 1, b: "hello world" }] }); // => { new: [] } (Type: { new: number[] }) | ||
``` |
@@ -0,4 +1,5 @@ | ||
import { Schema } from "./types/schema"; | ||
import { Transformed } from "./types/transformed"; | ||
import { reshaperBuilder } from "./reshape"; | ||
import { Schema, Transformed } from "./types"; | ||
export { reshaperBuilder, Schema, Transformed }; |
@@ -1,10 +0,17 @@ | ||
import { Reshaper, Schema, Transformed } from "./types"; | ||
import { Reshaper } from "./types/core"; | ||
import { Schema } from "./types/schema"; | ||
import { Transformed } from "./types/transformed"; | ||
const isDeclaredArrayTemplate = (template: unknown): template is [string, unknown] => { | ||
return Array.isArray(template) && template.length === 2 && typeof template[0] === "string"; | ||
}; | ||
function splitPath(path: string): string[] { | ||
return path.split(/\.|(\[\*\])|(\[\d+\])/g).filter((item) => item !== undefined && item !== ""); | ||
} | ||
const readField = <T>(o: T, field: string): unknown => { | ||
if (typeof o !== "object") { | ||
if (typeof o !== "object" || o === null) { | ||
return undefined; | ||
} | ||
if (o === null) { | ||
return o; | ||
} | ||
if (!Object.prototype.hasOwnProperty.call(o, field)) { | ||
@@ -17,49 +24,36 @@ return undefined; | ||
const handleArrayAccess = ( | ||
field: unknown, | ||
fieldName: string, | ||
path: string[] | ||
) => { | ||
const arrayAccessor = fieldName.split("["); | ||
const arrayName = arrayAccessor[0]; | ||
const arrayIndex = arrayAccessor[1].split("]")[0]; | ||
const array = readField(field, arrayName); | ||
if (array === undefined || array === null) { | ||
return array; | ||
} | ||
if (!Array.isArray(array)) { | ||
const handleArrayAccess = (array: unknown, index: string, path: string[]) => { | ||
if (array === undefined || array === null || !Array.isArray(array)) { | ||
return undefined; | ||
} | ||
if (arrayIndex === "*") { | ||
if (index === "[*]") { | ||
// Copy array to avoid mutation. | ||
const result = handleFlattenedArrayAccess(array, [...path]); | ||
if (path.find((item) => item.endsWith("[*]"))) { | ||
return result.flatMap((item) => | ||
item === undefined || item === null ? [] : item | ||
); | ||
if (path.find((item) => item === "[*]")) { | ||
return result.flatMap((item) => (item === undefined ? [] : item)); | ||
} | ||
return result; | ||
return result.filter((item) => item !== undefined); | ||
} else { | ||
return handleIndexedArrayAccess(array, parseInt(arrayIndex), [...path]); | ||
return handleIndexedArrayAccess(array, parseInt(index.slice(1, -1)), path); | ||
} | ||
}; | ||
const handleIndexedArrayAccess = ( | ||
array: unknown[], | ||
index: number, | ||
path: string[] | ||
): unknown => { | ||
const handleIndexedArrayAccess = (array: unknown[], index: number, path: string[]): unknown => { | ||
if (array.length <= index) { | ||
return undefined; | ||
} | ||
const result = fieldAccessor(array[index], [...path]); | ||
const result = fieldAccessor(array[index], path); | ||
return result; | ||
}; | ||
const handleFlattenedArrayAccess = ( | ||
array: unknown[], | ||
path: string[] | ||
): unknown[] => { | ||
return array | ||
.filter((item) => item !== undefined && item !== null) | ||
.map((item) => fieldAccessor(item, [...path])); | ||
const handleFlattenedArrayAccess = (array: unknown[], path: string[]): unknown[] => { | ||
if (path.length === 0) { | ||
return array.filter((item) => item !== undefined); | ||
} | ||
return ( | ||
array | ||
.filter((item) => item !== undefined && item !== null) | ||
// Path is used multiple times and must be copied. | ||
.map((item) => fieldAccessor(item, [...path])) | ||
); | ||
}; | ||
@@ -74,3 +68,4 @@ | ||
) { | ||
if (fieldName.endsWith("]")) { | ||
if (fieldName.match(/(\[\d+\])|(\[\*\])/g)) { | ||
// Array flattening is easier to handle recursively. | ||
return handleArrayAccess(field, fieldName, [...path]); | ||
@@ -84,28 +79,39 @@ } else { | ||
const objectConstructor = <T, S extends Schema<T>>( | ||
const arrayConstructor = <T>(data: T, template: [string, unknown]): unknown[] | undefined => { | ||
const path = template[0]; | ||
const array = fieldAccessor(data, splitPath(path)); | ||
if (!Array.isArray(array)) { | ||
return undefined; | ||
} | ||
const schema = template[1]; | ||
if (typeof schema === "string") { | ||
return array | ||
.map((item) => fieldAccessor(item, splitPath(schema))) | ||
.filter((item) => item !== undefined); | ||
} | ||
if (typeof schema !== "object" || schema === null) { | ||
return undefined; | ||
} | ||
if (isDeclaredArrayTemplate(schema)) { | ||
return array.map((item) => arrayConstructor(item, schema)).filter((item) => item !== undefined); | ||
} | ||
return array | ||
.map((item) => objectConstructor(item as never, schema as never)) | ||
.filter((item) => item !== undefined); | ||
}; | ||
const objectConstructor = <T extends Record<string, unknown>, S extends Schema<T>>( | ||
data: T, | ||
schema: S | ||
schema: S, | ||
): Transformed<T, S> => { | ||
const result: Record<string, unknown> = {}; | ||
for (const key in schema) { | ||
const item = schema[key]; | ||
if (typeof item === "string") { | ||
result[key] = fieldAccessor(data, item.split(".")); | ||
result[key] = fieldAccessor(data, splitPath(item)); | ||
} else if (typeof item === "object" && !Array.isArray(item)) { | ||
result[key] = objectConstructor(data, item as Schema<unknown>); | ||
} else { | ||
const fieldName = item[0] as string; | ||
const subSchema = item[1] as Schema<unknown>; | ||
const array = fieldAccessor(data, fieldName.split(".")); | ||
if (!Array.isArray(array)) { | ||
result[key] = undefined; | ||
} else { | ||
result[key] = array.map((item: unknown) => { | ||
if (typeof item !== "object") { | ||
return undefined; | ||
} | ||
return objectConstructor(item, subSchema); | ||
}); | ||
} | ||
result[key] = objectConstructor(data, item as never); | ||
} else if (isDeclaredArrayTemplate(item)) { | ||
result[key] = arrayConstructor(data, item); | ||
} | ||
@@ -116,8 +122,8 @@ } | ||
export const reshaperBuilder: <T, S extends Schema<T>>( | ||
schema: S | ||
) => Reshaper<T, S> = <T, S extends Schema<T>>( | ||
schema: S | ||
export const reshaperBuilder: <T extends Record<string, unknown>, S extends Schema<T>>( | ||
schema: S, | ||
) => Reshaper<T, S> = <T extends Record<string, unknown>, S extends Schema<T>>( | ||
schema: S, | ||
): ((data: T) => Transformed<T, S>) => { | ||
return (data: T) => objectConstructor(data, schema); | ||
}; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
57
561
74888
734