# remix-data-kit

> a kit to simplify handling form submissions in remix

Latest version **0.19.0** (published 2024-11-21) · MIT license · 0 weekly downloads

## Install

```sh
npm install remix-data-kit
pnpm add remix-data-kit
yarn add remix-data-kit
bun add remix-data-kit
```

Provides the command `remix-data-kit`.

## Health

**Score 40/100 (D)** — status: maintenance-mode.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads; pre 1.0.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.19.0 |
| Published | 2024-11-21 |
| First published | 2024-05-06 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=18 |
| Dependencies | 13 |
| Unpacked size | 110.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 3 |
| Author | Stephan Meijer |
| Maintainers | smeijer |
| Keywords | formdata, parse, stringify, expand |

## Links

- npm: https://www.npmjs.com/package/remix-data-kit
- Repository: https://github.com/smeijer/remix-data-kit
- Homepage: https://github.com/smeijer/remix-data-kit#readme
- Issues: https://github.com/smeijer/remix-data-kit/issues
- Funding: https://github.com/smeijer/remix-data-kit?sponsor=1
- npm.io page: https://npm.io/package/remix-data-kit

## Dependencies (13)

- [glob](https://npm.io/package/glob.md) ^10.3.12
- [bytes](https://npm.io/package/bytes.md) ^3.1.2
- [yargs](https://npm.io/package/yargs.md) ^17.7.2
- [busboy](https://npm.io/package/busboy.md) ^1.6.0
- [listr2](https://npm.io/package/listr2.md) ^8.2.1
- [picoid](https://npm.io/package/picoid.md) ^1.2.0
- [ts-morph](https://npm.io/package/ts-morph.md) ^23.0.0
- [picocolors](https://npm.io/package/picocolors.md) ^1.0.0
- [@types/bytes](https://npm.io/package/@types/bytes.md) ^3.1.4
- [@types/busboy](https://npm.io/package/@types/busboy.md) ^1.5.4
- [form-data-kit](https://npm.io/package/form-data-kit.md) ^1.1.0
- [schema2typebox](https://npm.io/package/schema2typebox.md) ^1.7.4
- [typebox-assert](https://npm.io/package/typebox-assert.md) ^0.5.0

## Alternatives

- [babylon](https://npm.io/package/babylon.md) — 5.1M weekly downloads
- [csscolorparser](https://npm.io/package/csscolorparser.md) — 3.7M weekly downloads
- [expr-eval-fork](https://npm.io/package/expr-eval-fork.md) — 1.5M weekly downloads
- [@leeoniya/ufuzzy](https://npm.io/package/@leeoniya/ufuzzy.md) — 247.7K weekly downloads
- [xml-parser](https://npm.io/package/xml-parser.md) — 78.4K weekly downloads

## Recent versions

- 0.19.0 (latest) — 2024-11-21
- 0.18.0 — 2024-09-18
- 0.17.0 — 2024-09-18
- 0.16.0 — 2024-05-31
- 0.15.0 — 2024-05-31
- 0.14.0 — 2024-05-31
- 0.12.0 — 2024-05-28
- 0.11.0 — 2024-05-15
- 0.10.0 — 2024-05-15
- 0.9.0 — 2024-05-15
- 0.8.0 — 2024-05-13
- 0.7.0 — 2024-05-10
- 0.6.0 — 2024-05-10
- 0.5.0 — 2024-05-09
- 0.4.0 — 2024-05-09
- … 4 more at https://npm.io/package/remix-data-kit/versions

## README

# remix-data-kit

> a kit to simplify remix actions / handling validated form data including file uploads.

## Install

```sh
npm install remix-data-kit
```

## Usage

We provide the `createActionHandler` method that creates a remix `ActionFunction`. In our actions, validated `data` is the first argument, remix `AppLoadContext` the second, and the remix default `ActionFunctionArgs` as third in case you'd really need it.

The data argument is the posted json, or FormData expanded using [form-data-kit]. Any file streams are piped to your `onFile` handler. No more manually handling FormData.

```ts
import { createActionHandler, createAction } from 'remix-data-kit';
import { Static, Type } from '@sinclair/typebox';
import { json } from '@remix-run/node';

export const CreateCommentSchema = Type.Object({
  body: Type.String({ minLength: 1, maxLength: 280 }),
  author: Type.String(),
});

const createComment = createAction({
  // the name is used as action intent
  name: 'create-comment',
  // schema to validate the posted json or FormData
  schema: CreateCommentSchema,
  // we provide data as first arg, and the context as second for convinience
  handler: async (data, { db }, args) => {
    // data is validated & typed!
    const inserted = await db.comments.insert(data);

    // return a remix/react-router valid response
    return json({ ok: true, comment: inserted });
  },
});

export const action = createActionHandler({
  createComment,
  // updateComment,
  // deleteComment,
});
```

Without `remix-data-kit` it would look something like this:

```ts
export const action = async ({ request, context }: ActionFunctionArgs) => {
  const formData = await request.formData();
  const _intent = formData.get('_intent');

  switch (_intent) {
    case 'create-comment': {
      assertUser(request);
      const body = formData.get('body').trim();
      const author = formData.get('author');

      if (body.length < 1 || body.length > 280) {
        throw json({ msg: 'invalid' }, { status: 422 });
      }

      const inserted = await db.comments.insert({ author, body });
      return json({ ok: true, comment: inserted });
    }

    case 'update-comment': {
      // ...
    }

    case 'delete-comment': {
      // ...
    }

    default: {
      throw json({ ok: false, message: `No handler found for action: ${_intent}` }, { status: 404 });
    }
  }
};
```

## Intent

We can't submit the forms without an intent, so let's handle that first. To make `remix-data-kit` understand your action intent, add one of the intent keys to your form `action` attribute:

```tsx
<form method="post" action="?/create-comment">
<form method="post" action="?action=create-comment">
<form method="post" action="?intent=create-comment">
```

It's a popular convention to use a named submit button, instead of this action url, but adding the intent to the url, allows us to extract the intent, before the full body is received, parsed, and validated. This way we can return a 404 before say all file uploads are processed.

## Validation

To ease validation, we're providing a [typebox] schema to our createAction method. Under the hood, we're using the `assertType` utility from [typebox-assert] to assert and narrow the type, and have wrapped that to throw a response instead of Error, that asserts and narrows the type of the submitted data.

`assertType` throws a `Response` with errors when the type is invalid. It also mutates the object to:

- remove additional properties that are not defined in the schema
- add missing properties by using schema defaults
- cast property types where possible

```ts
import { createActionHandler, createAction, assertType } from 'remix-data-kit';
import { Type, Static } from '@sinclair/typebox';

const CreateComment = Type.Object({
  body: Type.String(),
  tags: Type.String(),
});

export const action = createActionHandler({
  createComment: createAction({
    schema: CreateComment,
    handler: async (data) => {
      // data is typed as Static<CreateComment>
    },
  }),
});

// this would be the same:
export const action = createActionHandler({
  createComment: createAction({
    handler: async (data: unknown) => {
      assertType(CreateComment, data, 'data is not a valid comment');
      // data is narrowed to Static<CreateComment>
    },
  }),
});
```

Our recommendation is to use the `schema` property for actions, while using `assertType` to verify data structured from data that you fetch inside the actions, from say third party services.

## Expansion

We use [form-data-kit] to expand form data. Meaning, the data on your server is a structured json object even when form fields themselves are flat. For example:

```tsx
<input name="user.name" value="Alex" />
<input name="user.handle" value="@example" />
<input name="colors[].label" value="blue" />
<input name="colors[].label" value="red" />
<input name="colors[].label" value="green" />
```

Maps into:

```ts
const data = {
  user: { name: 'Alex', handle: '@example' },
  colors: [{ label: 'blue' }, { label: 'red' }, { label: 'green' }],
};
```

## File uploads

File uploads are handled by simply adding an `onFile` handler. Write the file to disk, or stream
it to another service provider. By the time all files are handled, the remaining payload is validated
and the `handler` is called to return a response.

```ts
import { assertType, readableStreamToFile } from 'remix-data-kit';

export const AttachmentSchema = Type.Object({
  id: Type.String(),
  files: Type.Array(
    Type.Object({
      id: Type.Number(),
      name: Type.String(),
      url: Type.String(),
    }),
  ),
});

export const createAttachmentAction = createAction({
  name: 'create-attachment',
  schema: AttachmentSchema,
  handler: (data) => {
    // here, data is of type Static<AttachmentSchema>, and `files` is
    // no longer a blob, but the meta data from the files
    return json({ ok: true, data });
  },
  // on file runs for every file upload (blob in FormData), and before handler
  onFile: async ({ file, info }) => {
    const blob = await uploadToS3({ file, info });
    // assign some data to `info` to make it available in `handler`,
    // be sure to match your schema type
    info.id = blob.id;
    info.url = blob.url;
  },
});
```

## Stream utilities

We're providing two stream utilities to make it easier to deal with file uploads.

**readableStreamToFile**, converts a ReadableStream to a File
**readableStreamToBlob**, converts a ReadableStream to a Blob

These methods make it trivial to map the stream into a format that can be provided to say FormData.

The `onFile` handler provides you with a Web ReadableStream, remember to use `Readable.fromWeb` if you'd need a Node stream.

## Limits

We support a couple of limits to manage how big a posted json object could be, or to accept only a certain file count of file type. The currently supported limits are:

- **fileCount** _number_

  The maximum number of files a user can upload. Note that empty file fields, still count against the file count limit.

- **fileSize** _number | string_

  The maximum size per file in bytes.

- **fieldSize** _number | string_;

  The maximum size of text fields.

- **jsonSize** _number | string_;

  The maximum size of json payloads.

- **mimeType** _string | string[]_;

  A valid [HTML accept](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept) string to restrict mime-types

Provide these to your action's limits property:

```ts
export const createAttachmentAction = createAction({
  name: 'create-attachment',
  schema: AttachmentSchema,
  handler: async (data) => {
    /* ... */
  },
  onFile: async ({ file, info }) => {
    /* ... */
  },
  limits: {
    fileCount: 3,
    fileSize: '1mb',
    fieldSize: '10kb',
    jsonSize: '150kb',
    mimeType: ['image/png', 'image/jpg'],
  },
});
```

## Content-Type

When using `createAction`, your endpoint suddenly supports not only FormData, but also json. Post using any of the content types:

- application/json
- application/x-www-form-urlencoded
- multipart/form-data

[typebox-assert]: https://npmjs.com/typebox-assert
[form-data-kit]: https://npmjs.com/form-data-kit
[typebox]: https://github.com/sinclairzx81/typebox

---
_Source: https://npm.io/package/remix-data-kit · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
