@gorhom/codable
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

Codable npm npm bundle size npm

A strict json parser inspired by Swift Codable ❤️

Alt text

Features

Works almost same as Swift Codable, but with some extra implementation to fit TypeScript / JavaScript environment.

  • Decodes JSON payload with pre-defined scheme.
    • Custom keys parsing.
    • Strict types checking.
    • Nested Codable parsing.

Supported Types

Types design was inspired by MobX State Tree ❤️

  • Primitives
    • String
    • Number
    • Boolean
  • Complex
    • Codable
    • Optional
    • Array
    • Date

Installation

yarn add @gorhom/codable
# or
npm install @gorhom/codable

Usage

import { BaseCodable, types, decode, encode } from '@gorhom/codable';
import dayjs from 'dayjs';

class Post extends BaseCodable {
  title!: string;
  isActive?: boolean;
  date!: Date;
}

Post.CodingProperties = {
  title: types.string,
  isActive: {
    type: types.optional(types.boolean),
    key: 'active',
  },
  date: types.date(dayjs),
};

class User extends BaseCodable {
  id!: number;
  username!: string;
  posts!: Post[];
}

User.CodingProperties = {
  id: types.number,
  username: types.string,
  posts: types.array(Post),
};

const jsonPayload = {
  id: 123,
  username: 'Gorhom',
  posts: [
    {
      title: 'dummy post',
      active: true,
      date: '2020-02-15T16:00:00.000Z',
    },
    {
      title: 'deleted post',
      active: false,
      date: '2020-02-10T16:00:00.000Z',
    },
  ],
};

const user: User = decode(User, jsonPayload);

// now encode it back 🙈
// ⚠️ date encoding still in progress

const userJson = encode(user)

TODO

Built With

Author

Package Sidebar

Install

npm i @gorhom/codable

Weekly Downloads

136

Version

1.1.1

License

MIT

Unpacked Size

113 kB

Total Files

34

Last publish

Collaborators

  • gorhom