forked from RangerMauve/gun-schema
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
68 lines (47 loc) · 1.22 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"use strict";
var globalVar = require("global");
var makeValidator = require("is-my-json-valid");
var Gun = globalVar.Gun || require("gun");
module.exports = makeSchema;
if (!Gun)
throw new Error("gun-schema: Gun was not found globally or via the bundle!");
makeSchema(Gun.chain);
function makeSchema(gun) {
gun.schema = addSchema;
gun.schemas = addSchemas;
gun.save = putValid;
}
function addSchemas(map, options) {
var gun = this;
var schemas = getSchemas(gun);
for (var key in schemas) {
var schema = schemas[key];
gun.schema(key, schema, options);
}
return gun;
}
function addSchema(name, schema, options) {
var gun = this;
var schemas = getSchemas(gun);
var validate = makeValidator(schema, options);
schemas[name] = validate;
return gun;
}
function putValid(name, value) {
var gun = this;
var schemas = getSchemas(gun);
var validate = schemas[name];
if (!validate)
throw new TypeError(name + " has not been registered as a type");
var valid = validate(value);
if (valid)
return gun.put(value);
var err = new TypeError("Value doesn't match schema for " + name);
err.errors = validate.errors;
throw err;
}
function getSchemas(gun) {
if (!gun._schemas)
gun._schemas = {};
return gun._schemas;
}