Skip to content

Commit

Permalink
docs: update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
dextertanyj committed May 5, 2023
1 parent a9ab9b3 commit 0ee212c
Showing 1 changed file with 158 additions and 11 deletions.
169 changes: 158 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@

TypeScript-first schema-based object transformation.

## 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.
Expand All @@ -20,15 +33,120 @@ Simply define a schema that describes the desired output using dot notation and
## Installation

```sh
$ npm install object-reshaper
```

### Requirements

- TypeScript 4.9+

```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 accssed 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"] },
],
};
```

| Path | Type | Value |
| ------------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | `number` | `1` |
| `name` | `{ first: string; last?: string }` | `{ first: "John", last: undefined }` |
| `name.first` | `string` | `"John"` |
| `name.last` | `string \| undefined` | `undefined` |
| `contact` or `contact[*]` | `number[]` | `[12345678]` |
| `contact[0]` | `number \| undefined` | `12345678` |
| `contact[1]` | `number \| undefined` | `undefined` |
| `posts` or `posts[*]` | `{ title: string; tags: string[] }[]` | `[` <br> &emsp;`{ title: "Hello World", tags: ["hello", "world"] }, ` <br> &emsp;`{ title: "My Second Post", tags: ["diary"] },`<br>`]` |
| `posts[*].title` | `string[]` | `["Hello World", "My Second Post"]` |
| `posts[*].tags` | `string[][]` | `[["hello", "world"], ["diary"]]` |
| `posts[*].tags[*]` | `string[]` | `["hello", "world", "diary"]` |

_\*The above list is not exhausitve._

### 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

Expand Down Expand Up @@ -64,7 +182,7 @@ const reshaper = reshaperBuilder<Input, typeof schema>(schema);
reshaper({ user: { address: { street: "home" } } }); // => { street: "home" } (Type: { street: string })
```

## Manipulating Arrays
### Manipulating Arrays

Accessing array elements

Expand Down Expand Up @@ -114,9 +232,7 @@ reshaper({ data: [{ nested: [1, 2] }, { nested: [3, 4] }] });
// => { new: [1,2,3,4] } (Type: { new: number[] })
```

_Support for multidimensional arrays coming soon_

## Transforming Objects Within Arrays
### Transforming Objects Within Arrays

Flatten nested arrays and transform elements

Expand All @@ -139,11 +255,42 @@ reshaper({
data: [
{ nested: [{ item: { id: 1, name: "first" } }] },
{
nested: [
{ item: { id: 2, name: "second" } },
{ item: { id: 3, name: "third" } },
],
nested: [{ item: { id: 2, name: "second" } }, { item: { id: 3, name: "third" } }],
},
],
}); // => { new: [{ new: 1 }, { new: 2 }, { new: 3 }] } (Type: { new: { new: number }[] })
```

## 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 comments on commit 0ee212c

Please sign in to comment.