Coder Social home page Coder Social logo

streamich / superjson Goto Github PK

View Code? Open in Web Editor NEW

This project forked from blitz-js/superjson

1.0 2.0 1.0 585 KB

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.

License: MIT License

TypeScript 95.75% JavaScript 4.15% Shell 0.10%

superjson's Introduction

superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.

All Contributors npm Language grade: JavaScript CI

Key features

  • 🍱 Reliable serialization and deserialization
  • πŸ” Type safety with autocompletion
  • 🐾 Negligible runtime footprint
  • πŸ’« Framework agnostic
  • πŸ›  Perfect fix for Next.js's serialisation limitations in getServerSideProps and getInitialProps

Backstory

At Blitz, we have struggled with the limitations of JSON. We often find ourselves working with Date, Map, Set or BigInt, but JSON.stringify doesn't support any of them without going through the hassle of converting manually!

Superjson solves these issues by providing a thin wrapper over JSON.stringify and JSON.parse.

Getting started

Install the library with your package manager of choice, e.g.:

yarn add superjson

Basic Usage

The easiest way to use Superjson is with its stringify and parse functions. If you know how to use JSON.stringify, you already know Superjson!

Easily stringify any expression you’d like:

import superjson from 'superjson';

const jsonString = superjson.stringify({ date: new Date(0) });

// jsonString === '{"json":{"date":"1970-01-01T00:00:00.000Z"},"meta":{"values":{date:"Date"}}}'

And parse your JSON like so:

const object = superjson.parse<{ date: Date }>(jsonString);

// object === { date: new Date(0) }

Advanced Usage

For cases where you want lower level access to the json and meta data in the output, you can use the serialize and deserialize functions.

One great use case for this is where you have an API that you want to be JSON compatible for all clients, but you still also want to transmit the meta data so clients can use superjson to fully deserialize it.

For example:

const object = {
  normal: 'string',
  timestamp: new Date(),
  test: /superjson/,
};

const { json, meta } = superjson.serialize(object);

/*
json = {
  normal: 'string',
  timestamp: "2020-06-20T04:56:50.293Z",
  test: "/blitz/",
};

// note that `normal` is not included here; `meta` only has special cases
meta = {
  values: {
    timestamp: ['date'],
    test: ['regexp'],
  }
};
*/

Using with Next.js

The getServerSideProps, getInitialProps, and getStaticProps data hooks provided by Next.js do not allow you to transmit Javascript objects like Dates. It will error unless you convert Dates to strings, etc.

Thankfully, Superjson is a perfect tool to bypass that limitation!

Install the library with your package manager of choice, e.g.:

yarn add -D babel-plugin-superjson-next

Add the plugin to your .babelrc. If you don't have one, create it.

{
  "presets": ["next/babel"],
  "plugins": [
    ...
    "superjson-next" // πŸ‘ˆ
  ]
}

Done! Now you can safely use all JS datatypes in your getServerSideProps / etc. .

API

serialize

Serializes any JavaScript value into a JSON-compatible object.

Examples

const object = {
  normal: 'string',
  timestamp: new Date(),
  test: /superjson/,
};

const { json, meta } = serialize(object);

Returns json and meta, both JSON-compatible values.

deserialize

Deserializes the output of Superjson back into your original value.

Examples

const { json, meta } = serialize(object);

deserialize({ json, meta });

Returns your original value.

stringify

Serializes and then stringifies your JavaScript value.

Examples

const object = {
  normal: 'string',
  timestamp: new Date(),
  test: /superjson/,
};

const jsonString = stringify(object);

Returns string.

parse

Parses and then deserializes the JSON string returned by stringify.

Examples

const jsonString = stringify(object);

parse(jsonString);

Returns string.


Superjson supports many extra types which JSON does not. You can serialize all these:

type supported by standard JSON? supported by Superjson?
string βœ… βœ…
number βœ… βœ…
boolean βœ… βœ…
null βœ… βœ…
Array βœ… βœ…
Object βœ… βœ…
undefined ❌ βœ…
bigint ❌ βœ…
Date ❌ βœ…
RegExp ❌ βœ…
Set ❌ βœ…
Map ❌ βœ…
Error ❌ βœ…

Recipes

SuperJSON by default only supports built-in data types to keep bundle-size as low as possible. Here are some recipes you can use to extend to non-default data types.

Place them in some central utility file and make sure they're executed before any other SuperJSON calls. In a Next.js project, _app.ts would be a good spot for that.

Decimal.js / Prisma.Decimal

import { Decimal }Β from "decimal.js"

SuperJSON.registerCustom<Decimal, string>(
  {
    isApplicable: (v): v is Decimal => Decimal.isDecimal(v),
    serialize: v => v.toJSON(),
    deserialize: v => new Decimal(v),
  },
  'decimal.js'
);

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Dylan Brookes

πŸ’» πŸ“– 🎨 ⚠️

Simon Knott

πŸ’» πŸ€” ⚠️ πŸ“–

Brandon Bayer

πŸ€”

Jeremy Liberman

⚠️ πŸ’»

Joris

πŸ’»

tomhooijenga

πŸ’»

AdemΓ­lson F. Tonato

⚠️

Piotr Monwid-Olechnowicz

πŸ€”

Alex Johansson

πŸ’» ⚠️

Simon Edelmann

πŸ› πŸ’» πŸ€”

Sam Garson

πŸ›

Mark Hughes

πŸ›

Lxxyx

πŸ’»

MΓ‘ximo Mussini

πŸ’»

Peter Dekkers

πŸ›

Gabe O'Leary

πŸ“–

This project follows the all-contributors specification. Contributions of any kind welcome!

Prior art

Other libraries that aim to solve a similar problem:

superjson's People

Contributors

allcontributors[bot] avatar dependabot[bot] avatar depfu[bot] avatar flybayer avatar ftonato avatar jorisre avatar katt avatar lxxyx avatar matthewmueller avatar merelinguist avatar mrleebo avatar skn0tt avatar tomhooijenga avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Forkers

ayazkhuraishi

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.