Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

serializr

Package Overview
Dependencies
Maintainers
1
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

serializr - npm Package Compare versions

Comparing version 1.1.11 to 1.1.12

7

CHANGELOG.md

@@ -0,1 +1,7 @@

# 1.1.12
* Improved documentation examples, see #43 by @brikou
* Fixed `class constructor cannot be invoked without 'new'` error, see #42 by @pinksquidhat
* Introduced `mapAsArray`, to support maps that serialize to arrays with objects with identifiers. And vice versa. By @vonovak. See #22
# 1.1.11

@@ -7,3 +13,2 @@

# 1.1.10

@@ -10,0 +15,0 @@

4

package.json
{
"name": "serializr",
"version": "1.1.11",
"version": "1.1.12",
"description": "Serialize and deserialize complex object graphs to JSON",

@@ -11,3 +11,3 @@ "main": "serializr.js",

"prepublish": "npm run small-build && npm run build-docs",
"small-build": "uglifyjs -m sort,toplevel -c --screw-ie8 --preamble '/** serializr - (c) Michel Weststrate 2016 - MIT Licensed */' --source-map serializr.min.js.map -o serializr.min.js serializr.js",
"small-build": "uglifyjs -m sort,toplevel -c --screw-ie8 --preamble \"/** serializr - (c) Michel Weststrate 2016 - MIT Licensed */\" --source-map serializr.min.js.map -o serializr.min.js serializr.js",
"build-docs": "documentation readme serializr.js --github --section API",

@@ -14,0 +14,0 @@ "build-test": "npm run build-test-babel && npm run build-test-ts",

@@ -9,2 +9,6 @@ # Serializr

_Serializr is feature complete, and easily extendable. Since there are no active maintainers the project is frozen feature wise. Bug reports are welcome and will be addressed._
Want to maintain a small open source project or having great ideas for this project? We are looking for maintainers, so [apply](https://github.com/mobxjs/serializr/issues/46)!
# Introduction

@@ -42,14 +46,21 @@

import {
createModelSchema, primitive, reference, list, object, identifier, serialize, deserialize
} from "serializr";
createModelSchema,
primitive,
reference,
list,
object,
identifier,
serialize,
deserialize,
} from 'serializr';
// Example model classes
class User {
uuid = Math.floor(Math.random()*10000);
displayName = "John Doe";
uuid = Math.floor(Math.random() * 10000);
displayName = 'John Doe';
}
class Message {
message = "Test";
author = null;
message = 'Test';
author = null;
comments = [];

@@ -61,4 +72,4 @@ }

// In a real app this might be a database query
const user = new User();
user.uuid = uuid;
const user = new User();
user.uuid = uuid;
user.displayName = `John Doe ${uuid}`;

@@ -73,3 +84,3 @@ return user;

// context is an object detailing the execution context of the serializer now
callback(null, fetchUserSomewhere(uuid))
callback(null, fetchUserSomewhere(uuid));
}

@@ -79,10 +90,10 @@

createModelSchema(Message, {
message : primitive(),
author : reference(User, findUserById),
comments: list(object(Message))
message: primitive(),
author: reference(User, findUserById),
comments: list(object(Message)),
});
createModelSchema(User, {
uuid : identifier(),
displayName: primitive()
uuid: identifier(),
displayName: primitive(),
});

@@ -92,10 +103,10 @@

const message = deserialize(Message, {
message : "Hello world",
author : 17,
message: 'Hello world',
author: 17,
comments: [
{
message: "Welcome!",
author : 23
}
]
message: 'Welcome!',
author: 23,
},
],
});

@@ -105,3 +116,3 @@

console.dir(message, {colors: true, depth: 10});
console.dir(message, { colors: true, depth: 10 });
```

@@ -115,7 +126,14 @@

import {
createModelSchema, primitive, reference, list, object, identifier, serialize, deserialize, getDefaultModelSchema,
serializable
} from "serializr";
createModelSchema,
primitive,
reference,
list,
object,
identifier,
serialize,
deserialize,
getDefaultModelSchema,
serializable,
} from 'serializr';
class User {

@@ -125,9 +143,7 @@ @serializable(identifier())

@serializable
displayName = "John Doe";
@serializable displayName = 'John Doe';
}
class Message {
@serializable
message = "Test";
@serializable message = 'Test';

@@ -144,18 +160,17 @@ @serializable(object(User))

const message = deserialize(Message, {
message : "Hello world",
author : {uuid: 1, displayName: "Alice"},
message: 'Hello world',
author: { uuid: 1, displayName: 'Alice' },
comments: [
{
message: "Welcome!",
author : {uuid: 1, displayName: "Bob"}
}
]
message: 'Welcome!',
author: { uuid: 1, displayName: 'Bob' },
},
],
});
console.dir(message, { colors: true, depth: 10 });
console.dir(message, {colors: true, depth: 10});
// We can call serialize without the first argument here
//because the schema can be inferred from the decorated classes
const json = serialize(message);

@@ -170,14 +185,15 @@ ```

class Message {
@serializable
message = "Test";
@serializable message = 'Test';
@serializable(object(User))
author = null;
comments = [];
constructor(){
getDefaultModelSchema(Message).props["comments"] = list(object(Message));
constructor() {
getDefaultModelSchema(Message).props['comments'] = list(
object(Message)
);
}
}
}
```

@@ -226,8 +242,8 @@

const todoSchema = {
factory: (context) => new Todo(),
factory: context => new Todo(),
extends: ModelSchema,
props: {
modelfield: PropSchema
}
}
modelfield: PropSchema,
},
};
```

@@ -290,12 +306,17 @@

<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
## ModelSchema
[serializr.js:128-135](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L128-L135 "Source code on GitHub")
[serializr.js:128-135](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L128-L135 "Source code on GitHub")
JSDOC type defintions for usage w/o typescript.
Type: [object](#object)
**Parameters**
- `value` **Any**
- `targetClass`
- `props`
- `value` **any**
- `writeable` **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
- `get` **([Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) \| [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined))**

@@ -305,17 +326,16 @@ - `set` **([Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) \| [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined))**

- `enumerable` **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
- `sourcePropertyValue` **Any**
- `jsonValue` **Any**
- `sourcePropertyValue` **any**
- `jsonValue` **any**
- `callback` **cpsCallback**
- `context` **Context**
- `writeable` **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
- `id` **Any**
- `target` **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `currentPropertyValue` **any**
- `id` **any**
- `target` **[object](#object)**
- `context` **Context**
- `result` **Any**
- `error` **Any**
- `result` **any**
- `error` **any**
- `id` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `callback` **cpsCallback**
- `factory`
- `props`
- `currentPropertyValue` **Any**
- `targetClass`

@@ -328,13 +348,13 @@ **Properties**

Returns **Any** any - serialized object
Returns **any** any - serialized object
Returns **Any** void
Returns **any** void
Returns **Any** void
Returns **any** void
Returns **Any** void
Returns **any** void
## createSimpleSchema
[serializr.js:128-135](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L128-L135 "Source code on GitHub")
[serializr.js:128-135](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L128-L135 "Source code on GitHub")

@@ -346,3 +366,3 @@ Creates a model schema that (de)serializes from / to plain javascript objects.

- `props` **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** property mapping,
- `props` **[object](#object)** property mapping,

@@ -353,15 +373,15 @@ **Examples**

var todoSchema = createSimpleSchema({
title: true,
done: true
title: true,
done: true,
});
var json = serialize(todoSchema, { title: "Test", done: false })
var todo = deserialize(todoSchema, json)
var json = serialize(todoSchema, { title: 'Test', done: false });
var todo = deserialize(todoSchema, json);
```
Returns **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** model schema
Returns **[object](#object)** model schema
## createModelSchema
[serializr.js:161-179](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L161-L179 "Source code on GitHub")
[serializr.js:161-179](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L161-L179 "Source code on GitHub")

@@ -375,3 +395,3 @@ Creates a model schema that (de)serializes an object created by a constructor function (class).

- `clazz` **([constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) | class)** class or constructor function
- `props` **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** property mapping
- `props` **[object](#object)** property mapping
- `factory` **[function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** optional custom factory. Receives context as first arg

@@ -383,20 +403,20 @@

function Todo(title, done) {
this.title = title;
this.done = done;
this.title = title;
this.done = done;
}
createModelSchema(Todo, {
title: true,
done: true
})
title: true,
done: true,
});
var json = serialize(new Todo("Test", false))
var todo = deserialize(Todo, json)
var json = serialize(new Todo('Test', false));
var todo = deserialize(Todo, json);
```
Returns **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** model schema
Returns **[object](#object)** model schema
## serializable
[serializr.js:210-220](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L210-L220 "Source code on GitHub")
[serializr.js:209-219](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L209-L219 "Source code on GitHub")

@@ -425,3 +445,3 @@ Decorator that defines a new property mapping on the default model schema for the class

[serializr.js:297-308](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L297-L308 "Source code on GitHub")
[serializr.js:292-303](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L292-L303 "Source code on GitHub")

@@ -434,20 +454,5 @@ The `serializeAll` decorator can be used on a class to signal that all primitive properties should be serialized automatically.

**Examples**
```javascript
\@serializeAll
class Store {
a = 3
b
}
const store = new Store
store.c = 5
store.d = {}
t.deepEqual(serialize(store), { a: 3, b: undefined, c: 5})
```
## getDefaultModelSchema
[serializr.js:316-325](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L316-L325 "Source code on GitHub")
[serializr.js:311-320](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L311-L320 "Source code on GitHub")

@@ -458,3 +463,3 @@ Returns the standard model schema associated with a class / constructor function

- `thing` **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `thing` **[object](#object)**

@@ -465,3 +470,3 @@ Returns **[ModelSchema](#modelschema)** model schema

[serializr.js:339-342](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L339-L342 "Source code on GitHub")
[serializr.js:334-337](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L334-L337 "Source code on GitHub")

@@ -484,3 +489,3 @@ Sets the default model schema for class / constructor function.

[serializr.js:394-412](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L394-L412 "Source code on GitHub")
[serializr.js:389-407](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L389-L407 "Source code on GitHub")

@@ -496,7 +501,7 @@ Serializes an object (graph) into json using the provided model schema.

Returns **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** serialized representation of the object
Returns **[object](#object)** serialized representation of the object
## deserialize
[serializr.js:470-488](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L470-L488 "Source code on GitHub")
[serializr.js:465-483](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L465-L483 "Source code on GitHub")

@@ -510,13 +515,13 @@ Deserializes a json structor into an object graph.

- `schema` **([object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) \| [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array))** to use for deserialization
- `schema` **([object](#object) \| [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array))** to use for deserialization
- `json` **[json](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON)** data to deserialize
- `callback` **[function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** node style callback that is invoked once the deserializaiton has finished.
First argument is the optional error, second argument is the deserialized object (same as the return value)
- `customArgs` **Any** custom arguments that are available as `context.args` during the deserialization process. This can be used as dependency injection mechanism to pass in, for example, stores.
- `customArgs` **any** custom arguments that are available as `context.args` during the deserialization process. This can be used as dependency injection mechanism to pass in, for example, stores.
Returns **([object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) \| [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array))** deserialized object, possibly incomplete.
Returns **([object](#object) \| [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array))** deserialized object, possibly incomplete.
## update
[serializr.js:657-678](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L657-L678 "Source code on GitHub")
[serializr.js:652-673](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L652-L673 "Source code on GitHub")

@@ -529,11 +534,11 @@ Similar to deserialize, but updates an existing object instance.

- `modelSchema` **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** , optional if it can be inferred from the instance type
- `target` **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** target instance to update
- `json` **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** the json to deserialize
- `modelSchema` **[object](#object)** , optional if it can be inferred from the instance type
- `target` **[object](#object)** target instance to update
- `json` **[object](#object)** the json to deserialize
- `callback` **[function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback to invoke once deserialization has completed.
- `customArgs` **Any** custom arguments that are available as `context.args` during the deserialization process. This can be used as dependency injection mechanism to pass in, for example, stores.
- `customArgs` **any** custom arguments that are available as `context.args` during the deserialization process. This can be used as dependency injection mechanism to pass in, for example, stores.
## primitive
##
[serializr.js:700-712](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L700-L712 "Source code on GitHub")
[serializr.js:679-679](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L679-L679 "Source code on GitHub")

@@ -546,6 +551,6 @@ Indicates that this field contains a primitive value (or Date) which should be serialized literally to json.

createModelSchema(Todo, {
title: primitive()
})
title: primitive(),
});
console.dir(serialize(new Todo("test")))
console.dir(serialize(new Todo('test')));
// outputs: { title : "test" }

@@ -558,3 +563,3 @@ ```

[serializr.js:751-765](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L751-L765 "Source code on GitHub")
[serializr.js:743-757](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L743-L757 "Source code on GitHub")

@@ -579,18 +584,16 @@ Similar to primitive, but this field will be marked as the identifier for the given Model type.

var s = _.createSimpleSchema({
id: _.identifier((id, object) => todos[id] = object),
title: true
})
id: _.identifier((id, object) => (todos[id] = object)),
title: true,
});
_.deserialize(s, {
id: 1, title: "test0"
})
_.deserialize(s, [
{ id: 2, title: "test2" },
{ id: 1, title: "test1" }
])
id: 1,
title: 'test0',
});
_.deserialize(s, [{ id: 2, title: 'test2' }, { id: 1, title: 'test1' }]);
t.deepEqual(todos, {
1: { id: 1, title: "test1" },
2: { id: 2, title: "test2" }
})
1: { id: 1, title: 'test1' },
2: { id: 2, title: 'test2' },
});
```

@@ -602,3 +605,3 @@

[serializr.js:776-791](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L776-L791 "Source code on GitHub")
[serializr.js:768-783](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L768-L783 "Source code on GitHub")

@@ -609,3 +612,3 @@ Similar to primitive, serializes instances of Date objects

[serializr.js:810-821](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L810-L821 "Source code on GitHub")
[serializr.js:802-813](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L802-L813 "Source code on GitHub")

@@ -624,6 +627,6 @@ Alias indicates that this model property should be named differently in the generated json.

createModelSchema(Todo, {
title: alias("task", primitive())
})
title: alias('task', primitive()),
});
console.dir(serialize(new Todo("test")))
console.dir(serialize(new Todo('test')));
// { task : "test" }

@@ -636,3 +639,3 @@ ```

[serializr.js:840-849](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L840-L849 "Source code on GitHub")
[serializr.js:836-845](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L836-L845 "Source code on GitHub")

@@ -650,9 +653,13 @@ Can be used to create simple custom propSchema.

var schema = _.createSimpleSchema({
a: _.custom(
function(v) { return v + 2 },
function(v) { return v - 2 }
)
})
t.deepEqual(_.serialize(s, { a: 4 }), { a: 6 })
t.deepEqual(_.deserialize(s, { a: 6 }), { a: 4 })
a: _.custom(
function(v) {
return v + 2;
},
function(v) {
return v - 2;
}
),
});
t.deepEqual(_.serialize(s, { a: 4 }), { a: 6 });
t.deepEqual(_.deserialize(s, { a: 6 }), { a: 4 });
```

@@ -664,3 +671,3 @@

[serializr.js:880-898](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L880-L898 "Source code on GitHub")
[serializr.js:875-893](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L875-L893 "Source code on GitHub")

@@ -679,18 +686,18 @@ `object` indicates that this property contains an object that needs to be (de)serialized

```javascript
class SubTask{}
class Todo{}
class SubTask {}
class Todo {}
createModelSchema(SubTask, {
title: true
title: true,
});
createModelSchema(Todo, {
title: true,
subTask: object(SubTask)
title: true,
subTask: object(SubTask),
});
const todo = deserialize(Todo, {
title: "Task",
subTask: {
title: "Sub task"
}
title: 'Task',
subTask: {
title: 'Sub task',
},
});

@@ -703,3 +710,3 @@ ```

[serializr.js:957-990](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L957-L990 "Source code on GitHub")
[serializr.js:950-983](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L950-L983 "Source code on GitHub")

@@ -715,7 +722,6 @@ `reference` can be used to (de)serialize references that point to other models.

`lookupFunction(identifier, callback, context)` where:
1\. `identifier` is the identifier being resolved
2\. `callback` is a node style calblack function to be invoked with the found object (as second arg) or an error (first arg)
3\. `context` see context.
1. `identifier` is the identifier being resolved
2. `callback` is a node style calblack function to be invoked with the found object (as second arg) or an error (first arg)
3. `context` see context.
The lookupFunction is optional. If it is not provided, it will try to find an object of the expected type and required identifier within the same JSON document

@@ -733,33 +739,33 @@

```javascript
class User{}
class Post{}
class User {}
class Post {}
createModelSchema(User, {
uuid: identifier(),
displayname: primitive()
})
uuid: identifier(),
displayname: primitive(),
});
createModelSchema(Post, {
author: reference(User, findUserById),
message: primitive()
})
author: reference(User, findUserById),
message: primitive(),
});
function findUserById(uuid, callback) {
fetch("http://host/user/" + uuid)
.then((userData) => {
deserialize(User, userData, callback)
})
.catch(callback)
fetch('http://host/user/' + uuid)
.then(userData => {
deserialize(User, userData, callback);
})
.catch(callback);
}
deserialize(
Post,
{
message: "Hello World",
author: 234
},
(err, post) => {
console.log(post)
}
)
Post,
{
message: 'Hello World',
author: 234,
},
(err, post) => {
console.log(post);
}
);
```

@@ -771,3 +777,3 @@

[serializr.js:1027-1048](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L1027-L1048 "Source code on GitHub")
[serializr.js:1021-1042](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L1021-L1042 "Source code on GitHub")

@@ -784,20 +790,22 @@ List indicates that this property contains a list of things.

```javascript
class SubTask{}
class Task{}
class Todo{}
class SubTask {}
class Task {}
class Todo {}
createModelSchema(SubTask, {
title: true
})
title: true,
});
createModelSchema(Todo, {
title: true,
subTask: list(object(SubTask))
})
title: true,
subTask: list(object(SubTask)),
});
const todo = deserialize(Todo, {
title: "Task",
subTask: [{
title: "Sub task 1"
}]
})
title: 'Task',
subTask: [
{
title: 'Sub task 1',
},
],
});
```

@@ -809,3 +817,3 @@

[serializr.js:1062-1111](https://github.com/mobxjs/serializr/blob/eb6d0a682e72f8a75645e3a016c501e26ba5c7c4/serializr.js#L1062-L1111 "Source code on GitHub")
[serializr.js:1056-1105](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L1056-L1105 "Source code on GitHub")

@@ -818,4 +826,19 @@ Similar to list, but map represents a string keyed dynamic collection.

- `propSchema` **Any**
- `propSchema` **any**
## mapAsArray
[serializr.js:1118-1154](https://github.com/mobxjs/serializr/blob/5a5ed016a487e4547204760153ab51addc32c851/serializr.js#L1118-L1154 "Source code on GitHub")
Similar to map, mapAsArray can be used to serialize a map-like collection where the key is contained in the 'value object'.
Example: consider Map&lt;id: number, customer: Customer> where the Customer object has the id stored on itself.
mapAsArray stores all values from the map into an array which is serialized.
Deserialization returns a ES6 Map or plain object object where the `keyPropertyName` of each object is used for keys.
For ES6 maps this has the benefit of being allowed to have non-string keys in the map. The serialized json also may be slightly more compact.
**Parameters**
- `propSchema` **any** , {string} keyPropertyName - the property of stored objects used as key in the map
- `keyPropertyName`
# Recipes and examples

@@ -830,13 +853,16 @@

task: primitive(),
owner: reference("_userId", UserStore.findUserById) // attribute of the owner attribute of a todo + lookup function
subTasks: alias("children", list(object(todoSchema)))
owner: reference('_userId', UserStore.findUserById), // attribute of the owner attribute of a todo + lookup function
subTasks: alias('children', list(object(todoSchema))),
},
};
const todo = deserialize(
todoSchema,
{ task: 'grab coffee', owner: 17, children: [] },
(err, todo) => {
console.log('finished loading todos');
}
}
const todo = deserialize(todoSchema,
{ task: "grab coffee", owner: 17, children: [] },
(err, todo) => { console.log("finished loading todos") }
);
const todoJson = serialize(todoSchema, todo)
const todoJson = serialize(todoSchema, todo);
```

@@ -852,17 +878,20 @@

const todoSchema = {
factory: (context) => new Todo(context.parent),
factory: context => new Todo(context.parent),
props: {
task: primitive(),
owner: reference("_userId", UserStore.findUserById) // attribute of the owner attribute of a todo + lookup function
subTasks: alias("children", list(object(todoSchema)))
owner: reference('_userId', UserStore.findUserById), // attribute of the owner attribute of a todo + lookup function
subTasks: alias('children', list(object(todoSchema))),
},
};
setDefaultModelSchema(Todo, todoSchema);
const todo = deserialize(
Todo, // just pass the constructor name, schema will be picked up
{ task: 'grab coffee', owner: 17, children: [] },
(err, todos) => {
console.log('finished loading todos');
}
}
setDefaultModelSchema(Todo, todoSchema)
const todo = deserialize(Todo, // just pass the constructor name, schema will be picked up
{ task: "grab coffee", owner: 17, children: [] },
(err, todos) => { console.log("finished loading todos") }
);
const todoJson = serialize(todo) // no need to pass schema explicitly
const todoJson = serialize(todo); // no need to pass schema explicitly
```

@@ -873,17 +902,18 @@

```javascript
function Todo() {
function Todo() {}
}
// creates a default factory, () => new Todo(), stores the schema as default model schema
createModelSchema(Todo, {
task: primitive()
})
task: primitive(),
});
const todo = deserialize(Todo, // just pass the constructor name, schema will be picked up
{ task: "grab coffee", owner: 17, children: [] },
(err, todos) => { console.log("finished loading todos") }
const todo = deserialize(
Todo, // just pass the constructor name, schema will be picked up
{ task: 'grab coffee', owner: 17, children: [] },
(err, todos) => {
console.log('finished loading todos');
}
);
const todoJson = serialize(todo) // no need to pass schema explicitly
const todoJson = serialize(todo); // no need to pass schema explicitly
```

@@ -896,8 +926,8 @@

@serializable(primitive())
task = "Grab coffee";
task = 'Grab coffee';
@serializable(reference("_userId", UserStore.findUserById))
@serializable(reference('_userId', UserStore.findUserById))
owner = null;
@serializable(alias("children", list(object(todoSchema)))
@serializable(alias('children', list(object(todoSchema))))
subTasks = [];

@@ -907,10 +937,17 @@ }

// note that (de)serialize also accepts lists
const todos = deserialize(Todo,
[{
task: "grab coffee", owner: 17, children: []
}],
(err, todos) => { console.log("finished loading todos") }
const todos = deserialize(
Todo,
[
{
task: 'grab coffee',
owner: 17,
children: [],
},
],
(err, todos) => {
console.log('finished loading todos');
}
);
const todoJson = serialize(todos)
const todoJson = serialize(todos);
```

@@ -921,9 +958,8 @@

```javascript
const someTodoStoreById = {}
const someTodoStoreById = {};
getDefaultModelSchema(Todo).factory = (context) => {
const json = context.json;
if (someTodoStoreById[json.id])
return someTodoStoreById[json.id] // reuse instance
return someTodoStoreById[json.id] = new Todo()
getDefaultModelSchema(Todo).factory = context => {
const json = context.json;
if (someTodoStoreById[json.id]) return someTodoStoreById[json.id]; // reuse instance
return (someTodoStoreById[json.id] = new Todo());
};

@@ -946,7 +982,7 @@ ```

createModelSchema(User, { username: true }, context => {
return new User(context.args.someStore)
})
return new User(context.args.someStore);
});
// don't want singletons!
const someStore = new SomeStore()
const someStore = new SomeStore();
// provide somestore through context of the deserialization process

@@ -956,7 +992,9 @@ const user = deserialize(

someJson,
(err, user) => { console.log("done") },
(err, user) => {
console.log('done');
},
{
someStore: someStore
someStore: someStore,
}
)
);
```

@@ -968,10 +1006,28 @@

// models.js:
import {observable, computed} from 'mobx';
import {serializable, identifier} from 'serializr';
import { observable, computed } from 'mobx';
import { serializable, identifier } from 'serializr';
function randomId() {
return Math.floor(Math.random()*100000);
return Math.floor(Math.random() * 100000);
}
export class Box {
<<<<<<< HEAD
@serializable(identifier())
id = randomId();
@serializable
@observable
x = 0;
@serializable
@observable
y = 0;
@serializable
@observable
location = 0;
constructor(location, x, y) {
=======
@serializable(identifier()) id = randomId();

@@ -981,4 +1037,5 @@ @serializable @observable x = 0;

@serializable @observable location = 0;
constructor(location, x, y){
>>>>>>> Updated readme and changelog
this.location = location;

@@ -988,4 +1045,10 @@ this.x = x;

}
<<<<<<< HEAD
@serializable
@computed
get area() {
=======
@serializable @computed get area() {
>>>>>>> Updated readme and changelog
return this.x * this.y;

@@ -995,12 +1058,24 @@ }

export class Arrow{
@serializable(identifier()) id = randomId();
@serializable(reference(Box)) from;
@serializable(reference(Box)) to;
export class Arrow {
@serializable(identifier())
id = randomId();
@serializable(reference(Box))
from;
@serializable(reference(Box))
to;
}
// store.js:
import {observable, transaction} from 'mobx';
import {createSimpleSchema, identifier, list, serialize, deserialize, update} from 'serializr';
import {Box, Arrow} from './models';
import { observable, transaction } from 'mobx';
import {
createSimpleSchema,
identifier,
list,
serialize,
deserialize,
update,
} from 'serializr';
import { Box, Arrow } from './models';

@@ -1011,3 +1086,3 @@ // The store that holds our domain: boxes and arrows

arrows: [],
selection: null
selection: null,
});

@@ -1019,3 +1094,3 @@

arrows: list(object(Arrow)),
selection: reference(Box)
selection: reference(Box),
});

@@ -1025,6 +1100,3 @@

// You can push data in as a class
store.boxes.push(
new Box('Rotterdam', 100, 100),
new Box('Vienna', 650, 300)
);
store.boxes.push(new Box('Rotterdam', 100, 100), new Box('Vienna', 650, 300));

@@ -1035,3 +1107,3 @@ // Or it can be an raw javascript object with the right properties

from: store.boxes[0],
to: store.boxes[1]
to: store.boxes[1],
});

@@ -1047,7 +1119,7 @@

update(storeModel, store, json);
})
});
}
// Print ... out for debugging
console.dir(serializeState(store), {depth: 10, colors: true});
console.dir(serializeState(store), { depth: 10, colors: true });
```

@@ -1054,0 +1126,0 @@

@@ -118,8 +118,8 @@ (function(g) {

* var todoSchema = createSimpleSchema({
* title: true,
* done: true
* title: true,
* done: true,
* });
*
* var json = serialize(todoSchema, { title: "Test", done: false })
* var todo = deserialize(todoSchema, json)
* var json = serialize(todoSchema, { title: 'Test', done: false });
* var todo = deserialize(todoSchema, json);
*

@@ -145,14 +145,14 @@ * @param {object} props property mapping,

* function Todo(title, done) {
* this.title = title;
* this.done = done;
* this.title = title;
* this.done = done;
* }
*
*
* createModelSchema(Todo, {
* title: true,
* done: true
* })
* title: true,
* done: true,
* });
*
* var json = serialize(new Todo('Test', false));
* var todo = deserialize(Todo, json);
*
* var json = serialize(new Todo("Test", false))
* var todo = deserialize(Todo, json)
*
* @param {constructor|class} clazz class or constructor function

@@ -192,17 +192,16 @@ * @param {object} props property mapping

* class Todo {
* @serializable(primitive())
* title;
*
* @serializable // shorthand for primitves
* done;
*
* constructor(title, done) {
* this.title = title;
* this.done = done;
* }
* @serializable(primitive())
* title; // shorthand for primitves
*
* @serializable done;
*
* constructor(title, done) {
* this.title = title;
* this.done = done;
* }
* }
*
* var json = serialize(new Todo('Test', false));
* var todo = deserialize(Todo, json);
*
* var json = serialize(new Todo("Test", false))
* var todo = deserialize(Todo, json)
*
* @param arg1

@@ -252,7 +251,3 @@ * @param arg2

// Create a factory so the constructor is called properly
factory = function(context) {
function F(args) {
return target.constructor.apply(this, args)
}
F.prototype = target.constructor.prototype
factory = function(context) {
var params = []

@@ -267,3 +262,4 @@ for (var i = 0; i < target.constructor.length; i++) {

}
return new F(params)
return new (Function.prototype.bind.apply(target.constructor, [null].concat(params)));
}

@@ -291,12 +287,11 @@ }

* @example
* \@serializeAll
* class Store {
* a = 3
* b
* @serializeAll class Store {
* a = 3;
* b;
* }
*
* const store = new Store
* store.c = 5
* store.d = {}
* t.deepEqual(serialize(store), { a: 3, b: undefined, c: 5})
*
* const store = new Store();
* store.c = 5;
* store.d = {};
* t.deepEqual(serialize(store), { a: 3, b: undefined, c: 5 });
*/

@@ -698,6 +693,6 @@ function serializeAll(target) {

* createModelSchema(Todo, {
* title: primitive()
* })
*
* console.dir(serialize(new Todo("test")))
* title: primitive(),
* });
*
* console.dir(serialize(new Todo('test')));
* // outputs: { title : "test" }

@@ -734,22 +729,19 @@ *

* var todos = {};
*
*
* var s = _.createSimpleSchema({
* id: _.identifier((id, object) => todos[id] = object),
* title: true
* })
*
* id: _.identifier((id, object) => (todos[id] = object)),
* title: true,
* });
*
* _.deserialize(s, {
* id: 1, title: "test0"
* })
* _.deserialize(s, [
* { id: 2, title: "test2" },
* { id: 1, title: "test1" }
* ])
*
* id: 1,
* title: 'test0',
* });
* _.deserialize(s, [{ id: 2, title: 'test2' }, { id: 1, title: 'test1' }]);
*
* t.deepEqual(todos, {
* 1: { id: 1, title: "test1" },
* 2: { id: 2, title: "test2" }
* })
* 1: { id: 1, title: 'test1' },
* 2: { id: 2, title: 'test2' },
* });
*
*
* @param {RegisterFunction} registerFn optional function to register this object during creation.

@@ -808,6 +800,6 @@ *

* createModelSchema(Todo, {
* title: alias("task", primitive())
* })
*
* console.dir(serialize(new Todo("test")))
* title: alias('task', primitive()),
* });
*
* console.dir(serialize(new Todo('test')));
* // { task : "test" }

@@ -837,9 +829,13 @@ *

* var schema = _.createSimpleSchema({
* a: _.custom(
* function(v) { return v + 2 },
* function(v) { return v - 2 }
* )
* })
* t.deepEqual(_.serialize(s, { a: 4 }), { a: 6 })
* t.deepEqual(_.deserialize(s, { a: 6 }), { a: 4 })
* a: _.custom(
* function(v) {
* return v + 2;
* },
* function(v) {
* return v - 2;
* }
* ),
* });
* t.deepEqual(_.serialize(s, { a: 4 }), { a: 6 });
* t.deepEqual(_.deserialize(s, { a: 6 }), { a: 4 });
*

@@ -868,19 +864,18 @@ * @param {function} serializer function that takes a model value and turns it into a json value

* @example
*
* class SubTask{}
* class Todo{}
*
* class SubTask {}
* class Todo {}
*
* createModelSchema(SubTask, {
* title: true
* title: true,
* });
* createModelSchema(Todo, {
* title: true,
* subTask: object(SubTask)
* title: true,
* subTask: object(SubTask),
* });
*
*
* const todo = deserialize(Todo, {
* title: "Task",
* subTask: {
* title: "Sub task"
* }
* title: 'Task',
* subTask: {
* title: 'Sub task',
* },
* });

@@ -930,35 +925,33 @@ *

* @example
*
*
* class User{}
* class Post{}
*
* class User {}
* class Post {}
*
* createModelSchema(User, {
* uuid: identifier(),
* displayname: primitive()
* })
*
* uuid: identifier(),
* displayname: primitive(),
* });
*
* createModelSchema(Post, {
* author: reference(User, findUserById),
* message: primitive()
* })
*
* author: reference(User, findUserById),
* message: primitive(),
* });
*
* function findUserById(uuid, callback) {
* fetch("http://host/user/" + uuid)
* .then((userData) => {
* deserialize(User, userData, callback)
* })
* .catch(callback)
* fetch('http://host/user/' + uuid)
* .then(userData => {
* deserialize(User, userData, callback);
* })
* .catch(callback);
* }
*
*
* deserialize(
* Post,
* {
* message: "Hello World",
* author: 234
* },
* (err, post) => {
* console.log(post)
* }
* )
* Post,
* {
* message: 'Hello World',
* author: 234,
* },
* (err, post) => {
* console.log(post);
* }
* );
*

@@ -1015,21 +1008,22 @@ * @param target: ModelSchema or string

* @example
*
* class SubTask{}
* class Task{}
* class Todo{}
*
* class SubTask {}
* class Task {}
* class Todo {}
*
* createModelSchema(SubTask, {
* title: true
* })
* title: true,
* });
* createModelSchema(Todo, {
* title: true,
* subTask: list(object(SubTask))
* })
*
* title: true,
* subTask: list(object(SubTask)),
* });
*
* const todo = deserialize(Todo, {
* title: "Task",
* subTask: [{
* title: "Sub task 1"
* }]
* })
* title: 'Task',
* subTask: [
* {
* title: 'Sub task 1',
* },
* ],
* });
*

@@ -1042,3 +1036,3 @@ * @param {PropSchema} propSchema to be used to (de)serialize the contents of the array

propSchema = propSchema || _defaultPrimitiveProp
invariant(isPropSchema(propSchema), "expected prop schema as second argument")
invariant(isPropSchema(propSchema), "expected prop schema as first argument")
invariant(!isAliasedPropSchema(propSchema), "provided prop is aliased, please put aliases first")

@@ -1078,3 +1072,3 @@ return {

propSchema = propSchema || _defaultPrimitiveProp
invariant(isPropSchema(propSchema), "expected prop schema as second argument")
invariant(isPropSchema(propSchema), "expected prop schema as first argument")
invariant(!isAliasedPropSchema(propSchema), "provided prop is aliased, please put aliases first")

@@ -1128,2 +1122,51 @@ return {

/**
* Similar to map, mapAsArray can be used to serialize a map-like collection where the key is contained in the 'value object'.
* Example: consider Map<id: number, customer: Customer> where the Customer object has the id stored on itself.
* mapAsArray stores all values from the map into an array which is serialized.
* Deserialization returns a ES6 Map or plain object object where the `keyPropertyName` of each object is used for keys.
* For ES6 maps this has the benefit of being allowed to have non-string keys in the map. The serialized json also may be slightly more compact.
*
* @param {any} propSchema, {string} keyPropertyName - the property of stored objects used as key in the map
* @returns
*/
function mapAsArray(propSchema, keyPropertyName) {
propSchema = propSchema || _defaultPrimitiveProp
invariant(isPropSchema(propSchema), "expected prop schema as first argument")
invariant(!!keyPropertyName, "expected key property name as second argument")
return {
serializer: function (m) {
var result = []
m.forEach(function (value, key) {
result.push(propSchema.serializer(value))
})
return result
},
deserializer: function (jsonArray, done, context, oldValue) {
list(propSchema).deserializer(
jsonArray,
function (err, values) {
if (err)
return void done(err)
var isMap = isMapLike(oldValue)
var newValue
if (isMap) {
oldValue.clear()
newValue = oldValue
} else
newValue = {}
for (var i = 0, l = jsonArray.length; i < l; i++)
if (isMap)
newValue.set(values[i][keyPropertyName], values[i])
else
newValue[values[i][keyPropertyName].toString()] = values[i]
done(null, newValue)
},
context
)
}
}
}
/*

@@ -1148,2 +1191,3 @@ * UMD shizzle

map: map,
mapAsArray: mapAsArray,
object: object,

@@ -1150,0 +1194,0 @@ child: object, // deprecate

/** serializr - (c) Michel Weststrate 2016 - MIT Licensed */
!function(e){"use strict";function r(){function e(e){if(e)throw new Error(e)}function r(e){var r=!1;return function(){return r?void t(!1,"callback was invoked twice"):(r=!0,e.apply(null,arguments))}}function t(e,r){if(!e)throw new Error("[serializr] "+(r||"Illegal State"))}function n(e,r,t){if(0===e.length)return void t(null,[]);var n=e.length,i=[],o=!1,a=function(e,r,a){r?o||(o=!0,t(r)):(i[e]=a,0===--n&&t(null,i))};e.forEach(function(e,t){r(e,a.bind(null,t))})}function i(e){return null===e||"object"!=typeof e&&"function"!=typeof e}function o(e){return{factory:function(){return{}},props:e}}function a(e,r,n){t(e!==Object,"one cannot simply put define a model schema for Object"),t("function"==typeof e,"expected constructor function");var i={targetClass:e,factory:n||function(){return new e},props:r};if(e.prototype.constructor!==Object){var o=f(e.prototype.constructor);o&&o.targetClass!==e&&(i.extends=o)}return p(e,i),i}function s(e,r,n){if(1===arguments.length){var i=e===!0?G:e;return t(h(i),"@serializable expects prop schema"),c.bind(null,i)}return c(O(),e,r,n)}function u(e){var r=e.toString().replace($,""),t=r.slice(r.indexOf("(")+1,r.indexOf(")")).match(B);return null===t&&(t=[]),t}function c(e,r,n,i){t(arguments.length>=2,"too few arguments. Please use @serializable as property decorator");var o;if(void 0===n&&"function"==typeof r&&r.prototype&&void 0!==i&&"number"==typeof i){t(h(e),"Constructor params must use alias(name)"),t(e.jsonname,"Constructor params must use alias(name)");var s=u(r);s.length>=i&&(n=s[i],e.paramNumber=i,i=void 0,r=r.prototype,o=function(e){function t(e){return r.constructor.apply(this,e)}t.prototype=r.constructor.prototype;for(var n=[],i=0;i<r.constructor.length;i++)Object.keys(e.modelSchema.props).forEach(function(r){var t=e.modelSchema.props[r];t.paramNumber===i&&(n[i]=e.json[t.jsonname])});return new t(n)})}t("string"==typeof n,"incorrect usage of @serializable decorator");var c=f(r);return c&&r.constructor.hasOwnProperty("serializeInfo")||(c=a(r.constructor,{},o)),c&&c.targetClass!==r.constructor&&(c=a(r.constructor,{},o)),c.props[n]=e,!i||i.get||i.set||(i.writable=!0),i}function l(e){t(1===arguments.length&&"function"==typeof e,"@serializeAll can only be used as class decorator");var r=f(e);return r&&e.hasOwnProperty("serializeInfo")||(r=a(e,{}),p(e,r)),f(e).props["*"]=!0,e}function f(e){return e?d(e)?e:d(e.serializeInfo)?e.serializeInfo:e.constructor&&e.constructor.serializeInfo?e.constructor.serializeInfo:void 0:null}function p(e,r){return t(d(r)),e.serializeInfo=r}function d(e){return e&&e.factory&&e.props}function h(e){return e&&e.serializer&&e.deserializer}function m(e){return"object"==typeof e&&!!e.jsonname}function v(e){return"object"==typeof e&&e.identifier===!0}function y(e){for(t(d(e));e;){for(var r in e.props)if("object"==typeof e.props[r]&&e.props[r].identifier===!0)return r;e=e.extends}return null}function g(e,r){for(;e;){if(e===r)return!0;e=e.extends}return!1}function b(e,r){t(1===arguments.length||2===arguments.length,"serialize expects one or 2 arguments");var n=1===arguments.length?e:r,i=1===arguments.length?null:e;if(Array.isArray(n)){if(0===n.length)return[];i||(i=f(n[0]))}else i||(i=f(n));return t(!!i,"Failed to find default schema for "+e),Array.isArray(n)?n.map(function(e){return z(i,e)}):z(i,n)}function z(e,r){t(e&&"object"==typeof e,"Expected schema"),t(r&&"object"==typeof r,"Expected object");var n;return n=e.extends?z(e.extends,r):{},Object.keys(e.props).forEach(function(i){var o=e.props[i];if("*"===i)return t(o===!0,"prop schema '*' can onle be used with 'true'"),void j(e,r,n);if(o===!0&&(o=G),o!==!1){var a=o.serializer(r[i],i,r);a!==U&&(n[o.jsonname||i]=a)}}),n}function j(e,r,t){for(var n in r)if(r.hasOwnProperty(n)&&!(n in e.props)){var o=r[n];i(o)&&(t[n]=o)}}function x(r,i,o,a){if(t(arguments.length>=2,"deserialize expects at least 2 arguments"),r=f(r),t(d(r),"first argument should be model schema"),Array.isArray(i)){var s=[];return n(i,function(e,t){var n=R(null,r,e,t,a);s.push(n)},o||e),s}return R(null,r,i,o,a)}function R(r,n,i,o,a){if(null===i||void 0===i)return void o(null,null);var s=new k(r,n,i,o,a),u=n.factory(s);t(!!u,"No object returned from factory"),s.target=u;var c=s.createCallback(e);return C(s,n,i,u),c(),u}function C(e,r,n,i){r.extends&&C(e,r.extends,n,i),Object.keys(r.props).forEach(function(o){var a=r.props[o];if("*"===o)return t(a===!0,"prop schema '*' can onle be used with 'true'"),void w(r,i,n);if(a===!0&&(a=G),a!==!1){var s=a.jsonname||o;s in n&&a.deserializer(n[s],e.rootContext.createCallback(function(e){e!==U&&(i[o]=e)}),e,i[o])}})}function S(e,r){for(var t in e.props)if("object"==typeof e.props[t]&&e.props[t].jsonname===r)return!0;return!1}function w(e,r,n){for(var o in n)if(!(o in e.props||S(e,o))){var a=n[o];t(i(a),"encountered non primitive value while deserializing '*' properties in property '"+o+"': "+a),r[o]=a}}function k(r,t,n,i,o){this.parentContext=r,this.isRoot=!r,this.pendingCallbacks=0,this.pendingRefsCount=0,this.onReadyCb=i||e,this.json=n,this.target=null,this.hasError=!1,this.modelSchema=t,this.isRoot?(this.rootContext=this,this.args=o,this.pendingRefs={},this.resolvedRefs={}):(this.rootContext=r.rootContext,this.args=r.args)}function E(r,n,i,o,a){var s=2===arguments.length||"function"==typeof arguments[2];s?(n=arguments[0],r=f(n),i=arguments[1],o=arguments[2],a=arguments[3]):r=f(r),t(d(r),"update failed to determine schema"),t("object"==typeof n&&n&&!Array.isArray(n),"update needs an object");var u=new k(null,r,i,o,a);u.target=n;var c=u.createCallback(e);C(u,r,i,n),c()}function O(){return{serializer:function(e){return t(i(e),"this value is not primitive: "+e),e},deserializer:function(e,r){return i(e)?void r(null,e):void r("[serializr] this value is not primitive: "+e)}}}function I(e){return t(!e||"function"==typeof e,"First argument should be ommitted or function"),{identifier:!0,serializer:G.serializer,deserializer:function(r,t,n){G.deserializer(r,function(r,i){A(i,n.target,n),e&&e(i,n.target,n),t(r,i)})}}}function A(e,r,t){t.rootContext.resolve(t.modelSchema,e,t.target)}function N(){return{serializer:function(e){return null===e||void 0===e?e:(t(e instanceof Date,"Expected Date object"),e.getTime())},deserializer:function(e,r){return null===e||void 0===e?void r(null,e):void r(null,new Date(e))}}}function P(e,r){return t(e&&"string"==typeof e,"expected prop name as first argument"),r=r&&r!==!0?r:G,t(h(r),"expected prop schema as second argument"),t(!m(r),"provided prop is already aliased"),{jsonname:e,serializer:r.serializer,deserializer:r.deserializer,identifier:v(r)}}function D(e,r){return t("function"==typeof e,"first argument should be function"),t("function"==typeof r,"second argument should be function"),{serializer:e,deserializer:function(e,t){t(null,r(e))}}}function M(e){return t("object"==typeof e||"function"==typeof e,"No modelschema provided. If you are importing it from another file be aware of circular dependencies."),{serializer:function(r){return e=f(e),t(d(e),"expected modelSchema, got "+e),null===r||void 0===r?r:b(e,r)},deserializer:function(r,n,i){return e=f(e),t(d(e),"expected modelSchema, got "+e),null===r||void 0===r?void n(null,r):void R(i,e,r,n)}}}function K(e,r){function n(){if(o=!0,t("string"!=typeof e||r,"if the reference target is specified by attribute name, a lookup function is required"),t(!r||"function"==typeof r,"second argument should be a lookup function"),"string"==typeof e)i=e;else{var n=f(e);t(d(n),"expected model schema or string as first argument for 'ref', got "+n),r=r||F(n),i=y(n),t(!!i,"provided model schema doesn't define an identifier() property and cannot be used by 'ref'.")}}t(!!e,"No modelschema provided. If you are importing it from another file be aware of circular dependencies.");var i,o=!1;return{serializer:function(e){return o||n(),e?e[i]:null},deserializer:function(e,t,i){o||n(),null===e||void 0===e?t(null,e):r(e,t,i)}}}function F(e){return function(r,t,n){n.rootContext.await(e,r,t)}}function J(e){return e=e||G,t(h(e),"expected prop schema as second argument"),t(!m(e),"provided prop is aliased, please put aliases first"),{serializer:function(r){return t(r&&"length"in r&&"map"in r,"expected array (like) object"),r.map(e.serializer)},deserializer:function(r,t,i){return Array.isArray(r)?void n(r,function(r,t){return e.deserializer(r,t,i)},t):void t("[serializr] expected JSON array")}}}function q(e){return e&&"function"==typeof e.keys&&"function"==typeof e.clear}function T(e){return e=e||G,t(h(e),"expected prop schema as second argument"),t(!m(e),"provided prop is aliased, please put aliases first"),{serializer:function(r){t(r&&"object"==typeof r,"expected object or Map");var n=q(r),i={};if(n)r.forEach(function(r,t){i[t]=e.serializer(r)});else for(var o in r)i[o]=e.serializer(r[o]);return i},deserializer:function(r,t,n,i){if(!r||"object"!=typeof r)return void t("[serializr] expected JSON object");var o=Object.keys(r);J(e).deserializer(o.map(function(e){return r[e]}),function(e,r){if(e)return void t(e);var n,a=q(i);a?(i.clear(),n=i):n={};for(var s=0,u=o.length;s<u;s++)a?n.set(o[s],r[s]):n[o[s]]=r[s];t(null,n)},n)}}}var U="undefined"!=typeof Symbol?Symbol("SKIP"):{SKIP:!0},$=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,B=/([^\s,]+)/g;k.prototype.createCallback=function(e){return this.pendingCallbacks++,r(function(r,t){r?this.hasError||(this.hasError=!0,this.onReadyCb(r)):this.hasError||(e(t),--this.pendingCallbacks===this.pendingRefsCount&&(this.pendingRefsCount>0?this.onReadyCb(new Error('Unresolvable references in json: "'+Object.keys(this.pendingRefs).filter(function(e){return this.pendingRefs[e].length>0},this).join('", "')+'"')):this.onReadyCb(null,this.target)))}.bind(this))},k.prototype.await=function(e,r,n){if(t(this.isRoot),r in this.resolvedRefs){var i=this.resolvedRefs[r].filter(function(r){return g(r.modelSchema,e)})[0];if(i)return void n(null,i.value)}this.pendingRefsCount++,this.pendingRefs[r]||(this.pendingRefs[r]=[]),this.pendingRefs[r].push({modelSchema:e,uuid:r,callback:n})},k.prototype.resolve=function(e,r,n){if(t(this.isRoot),this.resolvedRefs[r]||(this.resolvedRefs[r]=[]),this.resolvedRefs[r].push({modelSchema:e,value:n}),r in this.pendingRefs)for(var i=this.pendingRefs[r].length-1;i>=0;i--){var o=this.pendingRefs[r][i];g(e,o.modelSchema)&&(this.pendingRefs[r].splice(i,1),this.pendingRefsCount--,o.callback(null,n))}};var G=O();return{createModelSchema:a,createSimpleSchema:o,setDefaultModelSchema:p,getDefaultModelSchema:f,serializable:s,serialize:b,serializeAll:l,deserialize:x,update:E,primitive:O,identifier:I,date:N,alias:P,list:J,map:T,object:M,child:M,reference:K,ref:K,custom:D,SKIP:U}}"object"==typeof exports?module.exports=r():"function"==typeof define&&define.amd?define("serializr",[],r):e.serializr=r()}(function(){return this}());
!function(e){"use strict";function r(){function e(e){if(e)throw new Error(e)}function r(e){var r=!1;return function(){if(!r)return r=!0,e.apply(null,arguments);t(!1,"callback was invoked twice")}}function t(e,r){if(!e)throw new Error("[serializr] "+(r||"Illegal State"))}function n(e,r,t){if(0===e.length)return void t(null,[]);var n=e.length,i=[],o=!1,a=function(e,r,a){r?o||(o=!0,t(r)):(i[e]=a,0==--n&&t(null,i))};e.forEach(function(e,t){r(e,a.bind(null,t))})}function i(e){return null===e||"object"!=typeof e&&"function"!=typeof e}function o(e){return{factory:function(){return{}},props:e}}function a(e,r,n){t(e!==Object,"one cannot simply put define a model schema for Object"),t("function"==typeof e,"expected constructor function");var i={targetClass:e,factory:n||function(){return new e},props:r};if(e.prototype.constructor!==Object){var o=f(e.prototype.constructor);o&&o.targetClass!==e&&(i.extends=o)}return p(e,i),i}function s(e,r,n){if(1===arguments.length){var i=!0===e?H:e;return t(h(i),"@serializable expects prop schema"),c.bind(null,i)}return c(O(),e,r,n)}function u(e){var r=e.toString().replace(B,""),t=r.slice(r.indexOf("(")+1,r.indexOf(")")).match(G);return null===t&&(t=[]),t}function c(e,r,n,i){t(arguments.length>=2,"too few arguments. Please use @serializable as property decorator");var o;if(void 0===n&&"function"==typeof r&&r.prototype&&void 0!==i&&"number"==typeof i){t(h(e),"Constructor params must use alias(name)"),t(e.jsonname,"Constructor params must use alias(name)");var s=u(r);s.length>=i&&(n=s[i],e.paramNumber=i,i=void 0,r=r.prototype,o=function(e){for(var t=[],n=0;n<r.constructor.length;n++)Object.keys(e.modelSchema.props).forEach(function(r){var i=e.modelSchema.props[r];i.paramNumber===n&&(t[n]=e.json[i.jsonname])});return new(Function.prototype.bind.apply(r.constructor,[null].concat(t)))})}t("string"==typeof n,"incorrect usage of @serializable decorator");var c=f(r);return c&&r.constructor.hasOwnProperty("serializeInfo")||(c=a(r.constructor,{},o)),c&&c.targetClass!==r.constructor&&(c=a(r.constructor,{},o)),c.props[n]=e,!i||i.get||i.set||(i.writable=!0),i}function l(e){t(1===arguments.length&&"function"==typeof e,"@serializeAll can only be used as class decorator");var r=f(e);return r&&e.hasOwnProperty("serializeInfo")||(r=a(e,{}),p(e,r)),f(e).props["*"]=!0,e}function f(e){return e?d(e)?e:d(e.serializeInfo)?e.serializeInfo:e.constructor&&e.constructor.serializeInfo?e.constructor.serializeInfo:void 0:null}function p(e,r){return t(d(r)),e.serializeInfo=r}function d(e){return e&&e.factory&&e.props}function h(e){return e&&e.serializer&&e.deserializer}function m(e){return"object"==typeof e&&!!e.jsonname}function v(e){return"object"==typeof e&&!0===e.identifier}function g(e){for(t(d(e));e;){for(var r in e.props)if("object"==typeof e.props[r]&&!0===e.props[r].identifier)return r;e=e.extends}return null}function y(e,r){for(;e;){if(e===r)return!0;e=e.extends}return!1}function b(e,r){t(1===arguments.length||2===arguments.length,"serialize expects one or 2 arguments");var n=1===arguments.length?e:r,i=1===arguments.length?null:e;if(Array.isArray(n)){if(0===n.length)return[];i||(i=f(n[0]))}else i||(i=f(n));return t(!!i,"Failed to find default schema for "+e),Array.isArray(n)?n.map(function(e){return z(i,e)}):z(i,n)}function z(e,r){t(e&&"object"==typeof e,"Expected schema"),t(r&&"object"==typeof r,"Expected object");var n;return n=e.extends?z(e.extends,r):{},Object.keys(e.props).forEach(function(i){var o=e.props[i];if("*"===i)return t(!0===o,"prop schema '*' can onle be used with 'true'"),void j(e,r,n);if(!0===o&&(o=H),!1!==o){var a=o.serializer(r[i],i,r);a!==$&&(n[o.jsonname||i]=a)}}),n}function j(e,r,t){for(var n in r)if(r.hasOwnProperty(n)&&!(n in e.props)){var o=r[n];i(o)&&(t[n]=o)}}function x(r,i,o,a){if(t(arguments.length>=2,"deserialize expects at least 2 arguments"),r=f(r),t(d(r),"first argument should be model schema"),Array.isArray(i)){var s=[];return n(i,function(e,t){var n=R(null,r,e,t,a);s.push(n)},o||e),s}return R(null,r,i,o,a)}function R(r,n,i,o,a){if(null===i||void 0===i)return void o(null,null);var s=new k(r,n,i,o,a),u=n.factory(s);t(!!u,"No object returned from factory"),s.target=u;var c=s.createCallback(e);return C(s,n,i,u),c(),u}function C(e,r,n,i){r.extends&&C(e,r.extends,n,i),Object.keys(r.props).forEach(function(o){var a=r.props[o];if("*"===o)return t(!0===a,"prop schema '*' can onle be used with 'true'"),void w(r,i,n);if(!0===a&&(a=H),!1!==a){var s=a.jsonname||o;s in n&&a.deserializer(n[s],e.rootContext.createCallback(function(e){e!==$&&(i[o]=e)}),e,i[o])}})}function S(e,r){for(var t in e.props)if("object"==typeof e.props[t]&&e.props[t].jsonname===r)return!0;return!1}function w(e,r,n){for(var o in n)if(!(o in e.props||S(e,o))){var a=n[o];t(i(a),"encountered non primitive value while deserializing '*' properties in property '"+o+"': "+a),r[o]=a}}function k(r,t,n,i,o){this.parentContext=r,this.isRoot=!r,this.pendingCallbacks=0,this.pendingRefsCount=0,this.onReadyCb=i||e,this.json=n,this.target=null,this.hasError=!1,this.modelSchema=t,this.isRoot?(this.rootContext=this,this.args=o,this.pendingRefs={},this.resolvedRefs={}):(this.rootContext=r.rootContext,this.args=r.args)}function E(r,n,i,o,a){2===arguments.length||"function"==typeof arguments[2]?(n=arguments[0],r=f(n),i=arguments[1],o=arguments[2],a=arguments[3]):r=f(r),t(d(r),"update failed to determine schema"),t("object"==typeof n&&n&&!Array.isArray(n),"update needs an object");var s=new k(null,r,i,o,a);s.target=n;var u=s.createCallback(e);C(s,r,i,n),u()}function O(){return{serializer:function(e){return t(i(e),"this value is not primitive: "+e),e},deserializer:function(e,r){return i(e)?void r(null,e):void r("[serializr] this value is not primitive: "+e)}}}function A(e){return t(!e||"function"==typeof e,"First argument should be ommitted or function"),{identifier:!0,serializer:H.serializer,deserializer:function(r,t,n){H.deserializer(r,function(r,i){I(i,n.target,n),e&&e(i,n.target,n),t(r,i)})}}}function I(e,r,t){t.rootContext.resolve(t.modelSchema,e,t.target)}function N(){return{serializer:function(e){return null===e||void 0===e?e:(t(e instanceof Date,"Expected Date object"),e.getTime())},deserializer:function(e,r){return null===e||void 0===e?void r(null,e):void r(null,new Date(e))}}}function P(e,r){return t(e&&"string"==typeof e,"expected prop name as first argument"),r=r&&!0!==r?r:H,t(h(r),"expected prop schema as second argument"),t(!m(r),"provided prop is already aliased"),{jsonname:e,serializer:r.serializer,deserializer:r.deserializer,identifier:v(r)}}function D(e,r){return t("function"==typeof e,"first argument should be function"),t("function"==typeof r,"second argument should be function"),{serializer:e,deserializer:function(e,t){t(null,r(e))}}}function M(e){return t("object"==typeof e||"function"==typeof e,"No modelschema provided. If you are importing it from another file be aware of circular dependencies."),{serializer:function(r){return e=f(e),t(d(e),"expected modelSchema, got "+e),null===r||void 0===r?r:b(e,r)},deserializer:function(r,n,i){return e=f(e),t(d(e),"expected modelSchema, got "+e),null===r||void 0===r?void n(null,r):void R(i,e,r,n)}}}function F(e,r){function n(){if(o=!0,t("string"!=typeof e||r,"if the reference target is specified by attribute name, a lookup function is required"),t(!r||"function"==typeof r,"second argument should be a lookup function"),"string"==typeof e)i=e;else{var n=f(e);t(d(n),"expected model schema or string as first argument for 'ref', got "+n),r=r||K(n),i=g(n),t(!!i,"provided model schema doesn't define an identifier() property and cannot be used by 'ref'.")}}t(!!e,"No modelschema provided. If you are importing it from another file be aware of circular dependencies.");var i,o=!1;return{serializer:function(e){return o||n(),e?e[i]:null},deserializer:function(e,t,i){o||n(),null===e||void 0===e?t(null,e):r(e,t,i)}}}function K(e){return function(r,t,n){n.rootContext.await(e,r,t)}}function J(e){return e=e||H,t(h(e),"expected prop schema as first argument"),t(!m(e),"provided prop is aliased, please put aliases first"),{serializer:function(r){return t(r&&"length"in r&&"map"in r,"expected array (like) object"),r.map(e.serializer)},deserializer:function(r,t,i){if(!Array.isArray(r))return void t("[serializr] expected JSON array");n(r,function(r,t){return e.deserializer(r,t,i)},t)}}}function q(e){return e&&"function"==typeof e.keys&&"function"==typeof e.clear}function T(e){return e=e||H,t(h(e),"expected prop schema as first argument"),t(!m(e),"provided prop is aliased, please put aliases first"),{serializer:function(r){t(r&&"object"==typeof r,"expected object or Map");var n=q(r),i={};if(n)r.forEach(function(r,t){i[t]=e.serializer(r)});else for(var o in r)i[o]=e.serializer(r[o]);return i},deserializer:function(r,t,n,i){if(!r||"object"!=typeof r)return void t("[serializr] expected JSON object");var o=Object.keys(r);J(e).deserializer(o.map(function(e){return r[e]}),function(e,r){if(e)return void t(e);var n,a=q(i);a?(i.clear(),n=i):n={};for(var s=0,u=o.length;s<u;s++)a?n.set(o[s],r[s]):n[o[s]]=r[s];t(null,n)},n)}}}function U(e,r){return e=e||H,t(h(e),"expected prop schema as first argument"),t(!!r,"expected key property name as second argument"),{serializer:function(r){var t=[];return r.forEach(function(r,n){t.push(e.serializer(r))}),t},deserializer:function(t,n,i,o){J(e).deserializer(t,function(e,i){if(e)return void n(e);var a,s=q(o);s?(o.clear(),a=o):a={};for(var u=0,c=t.length;u<c;u++)s?a.set(i[u][r],i[u]):a[i[u][r].toString()]=i[u];n(null,a)},i)}}}var $="undefined"!=typeof Symbol?Symbol("SKIP"):{SKIP:!0},B=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,G=/([^\s,]+)/g;k.prototype.createCallback=function(e){return this.pendingCallbacks++,r(function(r,t){r?this.hasError||(this.hasError=!0,this.onReadyCb(r)):this.hasError||(e(t),--this.pendingCallbacks===this.pendingRefsCount&&(this.pendingRefsCount>0?this.onReadyCb(new Error('Unresolvable references in json: "'+Object.keys(this.pendingRefs).filter(function(e){return this.pendingRefs[e].length>0},this).join('", "')+'"')):this.onReadyCb(null,this.target)))}.bind(this))},k.prototype.await=function(e,r,n){if(t(this.isRoot),r in this.resolvedRefs){var i=this.resolvedRefs[r].filter(function(r){return y(r.modelSchema,e)})[0];if(i)return void n(null,i.value)}this.pendingRefsCount++,this.pendingRefs[r]||(this.pendingRefs[r]=[]),this.pendingRefs[r].push({modelSchema:e,uuid:r,callback:n})},k.prototype.resolve=function(e,r,n){if(t(this.isRoot),this.resolvedRefs[r]||(this.resolvedRefs[r]=[]),this.resolvedRefs[r].push({modelSchema:e,value:n}),r in this.pendingRefs)for(var i=this.pendingRefs[r].length-1;i>=0;i--){var o=this.pendingRefs[r][i];y(e,o.modelSchema)&&(this.pendingRefs[r].splice(i,1),this.pendingRefsCount--,o.callback(null,n))}};var H=O();return{createModelSchema:a,createSimpleSchema:o,setDefaultModelSchema:p,getDefaultModelSchema:f,serializable:s,serialize:b,serializeAll:l,deserialize:x,update:E,primitive:O,identifier:A,date:N,alias:P,list:J,map:T,mapAsArray:U,object:M,child:M,reference:F,ref:F,custom:D,SKIP:$}}"object"==typeof exports?module.exports=r():"function"==typeof define&&define.amd?define("serializr",[],r):e.serializr=r()}(function(){return this}());
//# sourceMappingURL=serializr.min.js.map

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc