• Stars
    star
    250
  • Rank 162,397 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Transit serialisation for Immutable.js

transit-immutable-js

Transit serialisation for Immutable.js.

Transit is a serialisation format which builds on top of JSON to provide a richer set of types. It is extensible, which makes it a good choice for easily providing serialisation and deserialisation capabilities for Immutable's types.

npm version Build Status Coverage Status MIT Licensed

Install

npm install transit-immutable-js

You must also be using immutable for this to be of any use.

I have chosen to apply very broad npm peerDependencies for simplicity, please check that the versions you have pulled in actually work.

Usage

var transit = require('transit-immutable-js');
var Immutable = require('immutable');

var m = Immutable.Map({with: "Some", data: "In"});

var str = transit.toJSON(m);

console.log(str)
// ["~#cmap",["with","Some","data","In"]]

var m2 = transit.fromJSON(str);

console.log(Immutable.is(m, m2));
// true

This library also manages to preserve objects which are a mixture of plain javascript and Immutable.

var obj = {
  iMap: Immutable.Map().set(Immutable.List.of(1, 2, 3), "123"),
  iList: Immutable.List.of("a", "b", "c"),
  array: [ "javascript", 4, "lyfe" ]
}

console.log(transit.fromJSON(transit.toJSON(obj)));
// { iMap: Map { [1,2,3]: "123" },
//  iList: List [ "a", "b", "c" ],
//  array: [ 'javascript', 4, 'lyfe' ] }

Usage with transit directly

As well as the nice friendly wrapped API, the internal handlers are exposed in case you need to work directly with the transit-js API.

var transitJS = require('transit-js');
var handlers = require('transit-immutable-js').handlers;

var reader = transitJS.reader('json', {handlers: handlers.read});
var writer = transitJS.writer('json-verbose', {handlers: handlers.write});

API

transit.toJSON(object) => string

Convert an immutable object into a JSON representation (XSS Warning)

transit.fromJSON(string) => object

Convert a JSON representation back into an immutable object

transit.handlers.read object

A mapping of tags to decoding functions which can be used to create a transit reader directly.

transit.handlers.write transit.map

A mapping of type constructors to encoding functions which can be used to create a transit writer directly.

The various withXXX methods can be combined as desired by chaining them together.

transit.withExtraHandlers(Array handlers) => transit

Also transit.handlers.withExtraHandlers(Array handlers) => handlers

Create a modified version of the transit API that knows about more types than it did before. This is primarily useful if you have additional custom datatypes that you want to be able serialise and deserialise. Each entry in this array must be an object with the following properties:

  • tag string - a unique identifier for this type that will be used in the serialised output
  • class function - a constructor function that can be used to identify the type via an instanceof check
  • write function(value) - a function which will receive an instance of your type, and is expected to create some serialisable representation of it
  • read function(rep) - a function which will receive the serialisable representation, and is expected to create a new instance from it

The read and write functions should form a matched pair of functions - calling read on the result of write should produce the same value and vice versa. Transit applies encoding and decoding recursively, so you can return any type transit understands from write, and expect to receive it back in read later.

transit.withFilter(function) => transit

Also transit.handlers.withFilter(function) => handlers

Create a modified version of the transit API that deeply applies the provided filter function to all immutable collections before serialising. Can be used to exclude entries.

transit.withRecords(Array recordClasses, missingRecordHandler = null) => transit

Also transit.handlers.withRecords(Array recordClasses, missingRecordHandler = null) => handlers

Creates a modified version of the transit API with support for serializing/deserializing Record objects. If a Record is included in an object to be serialized without the proper handler, on encoding it will be encoded as an Immutable.Map.

missingRecordHandler is called when a record-name is not found and can be used to handle the missing record manually. If no handler is given, the deserialisation process will throw an error. It accepts 2 parameters: name and value and the return value will be used instead of the missing record.

Example Record Usage:

var FooRecord = Immutable.Record({
  a: 1,
  b: 2,
}, 'foo');

var data = new FooRecord();

var recordTransit = transit.withRecords([FooRecord]);
var encodedJSON = recordTransit.toJSON(data);

Example missing Record Usage:

var BarRecord = Immutable.Record({
  c: '1',
  d: '2'
}, 'bar');

var FooRecord = Immutable.Record({
  a: 1,
  b: 2,
}, 'foo');

var data = new FooRecord({a: 3, b: 4});

var recordTransitFoo = transit.withRecords([FooRecord]);
var encodedJSON = recordTransitFoo.toJSON(data);

var recordTransitEmpty = transit.withRecords([], function (name, value) {
  switch (name) {
    case 'foo':
      return new BarRecord({c: value.a, d: value.b});
    default:
      return null;
  }
});

var decodedResult = recordTransitEmpty.fromJSON(encodedJSON); // returns new BarRecord({c: 3, d: 4})

XSS Warning

When embedding JSON in an html page or related context (e.g. css, element attributes, etc), care must be taken to sanitize the output. By design, niether transit-js nor transit-immutable-js provide output sanitization.

There are a number of libraries that can help. Including: xss-filters, secure-filters, and many more

More Repositories

1

ultimate-hot-reloading-example

Hot reload all the things!
JavaScript
962
star
2

skin-deep

Test assertion helpers for use with React's shallowRender test utils
JavaScript
200
star
3

node-fib

Fast non-blocking fibonacci server
JavaScript
129
star
4

devboard

An interactive visual feedback tool for developing user interface code
JavaScript
87
star
5

mocha-multi

A bit of a hack to get multiple reporters working with mocha
JavaScript
75
star
6

jenkins-groovy-examples

Some samples of groovy scripts used in jenkins automation
47
star
7

ReactNativeFlexboxPlayground

Demo app to make it easy to experiment with flexbox layouts
JavaScript
40
star
8

react-hotkey

A simple mixin for application hotkeys
JavaScript
35
star
9

fluctuations

Yet another flux implementation
JavaScript
26
star
10

checkers

Property-based testing for JavaScript via ClojureScript's test.check
JavaScript
21
star
11

pretty-immutable

Pretty printing for ImmutableJS
JavaScript
12
star
12

cljs-webpack-deps

Trying out using npm dependencies via webpack in clojurescript.
Clojure
10
star
13

terrafiddle

Mini ruby dsl for generating terraform files
Ruby
9
star
14

node_modules

A curated list of beautiful node_modules that I like to use.
Makefile
7
star
15

typescript-xunit-xml

Produce xUnit-style XML output from typescript compiler messages
JavaScript
6
star
16

nodespec

A light-weight RSpec-esque testing framework for NodeJS with pluggable extensibility. I now recommend Mocha
JavaScript
6
star
17

hack-react-app

Zero Configuration, or is it?
JavaScript
6
star
18

fourten

An opinionated Go HTTP Client.
Go
5
star
19

git-mnemonic

Speakable, rememberable translations for git ref hashes
Python
5
star
20

npm-t-shirt

Bringing t-shirts to npm, sort of
JavaScript
5
star
21

react-calendar

Calendar example in React
JavaScript
4
star
22

phptea

A simple, flexible test harness for specifying tests in a SpecBDD style.
PHP
4
star
23

azure-terraform-generate

Generate terraform config from deployed azure resources.
Python
4
star
24

babblog-royale

Babble Royale log parser and viewer
TypeScript
3
star
25

vagrant-provider

Vagrant plugin for provider swapping
Ruby
3
star
26

react-element-to-string

Convert a ReactElement into a nice string useful for debugging
JavaScript
3
star
27

react-testing-workshop

Code for React Testing Workshop at jsconfco 2016.
JavaScript
3
star
28

byte-board

Like a whiteboard, but with bytes.
Elm
3
star
29

webpack-hot-client-overlay

An overlay for webpack-hot-client
JavaScript
2
star
30

present-express

Presenters + Hogan (mustache) for express
JavaScript
2
star
31

node-tracey

Find out how you got somewhere
JavaScript
2
star
32

flow-stuck-repro

JavaScript
2
star
33

q

Fakes stubs and spies for Clojure testing
Clojure
2
star
34

kaniko-publish-orb

CircleCI Orb to build and publish container images to container registries *without* docker.
Dockerfile
2
star
35

node-intro

Presentation and example sources for a NodeJS introduction
JavaScript
2
star
36

connect-hopeful-body-parser

Attempt to parse body data without an Accept header
JavaScript
2
star
37

CanDB

Database for storing potential recruitment candidates
JavaScript
2
star
38

github-cookbook

Chef Library Cookbook for declaring resources on GitHub
Ruby
1
star
39

in-the-loop

Simple pub/sub on a single HTML page - handy for hackday activity feeds
JavaScript
1
star
40

nodeschool-learnyounode

Solutions to nodeschool.io's learnyounode tutorial
JavaScript
1
star
41

raspbian-kiosk-maker

Some ansible-powered steps to getting a super-simple information radiator on a raspberry pi
1
star
42

shared-user-agent

A simple way to click links on one computer and have them open on another
Python
1
star
43

zombie-server

A REST-like HTTP server wrapping zombie.js sessions
JavaScript
1
star
44

merb-breadcrumbs

A simple merb plugin to provide useful hooks for breadcrumb links.
Ruby
1
star
45

epic-trello

An attempt at providing an epic-level view across a trello board.
JavaScript
1
star
46

magic-of-hot-code

Code samples for talk
JavaScript
1
star
47

lein-new-reflection

Clojure
1
star
48

eslint-samples

My standard eslint configs
JavaScript
1
star
49

ribbit

Provides a Module to handle sending notifications to hoptoad.
Ruby
1
star
50

not-talking

Slides for presentation on "Scaling Agile by not Talking to Each Other"
CSS
1
star
51

circles-and-arrows

HTML Canvas based Super-simple State Machine Diagram Tool
JavaScript
1
star
52

defmulti

Flexible JavaScript polymorphism without requiring inheritance or object orientism
JavaScript
1
star
53

tel

Super simple DI for JavaScript, targetted mainly at spec test setup
JavaScript
1
star
54

node-intro-challenge

Short programming excercise as a companion to a NodeJS intro presentation
JavaScript
1
star
55

glenjamin.github.com

Github presence
JavaScript
1
star
56

confident-user-interface-programming

A talk at CodeMesh 2016 by Glen Mailer
1
star
57

emojifight

Hot Module Reloading demo application
JavaScript
1
star
58

video-voting

Video Voting App for youtube movie nights
JavaScript
1
star
59

BehatMultiFormatter

A Behat extension adding a multipage HTML formatter with index and summary
1
star
60

node-controlled-amd

An AMD loader for NodeJS that keeps you in control by using minimal magic. Aimed primarily at loading frontend modules for unit testing.
JavaScript
1
star