1 | import Property from './property';
|
2 | import { identity } from './utilities';
|
3 | import { assert, isUndefined, isObject, isFunction } from './assertions';
|
4 |
|
5 | const internal = {};
|
6 |
|
7 | internal.empty = val => val == null;
|
8 | internal.nullOrType = type => val => !val ? null : type(val);
|
9 | internal.zeroOrNumber = val => !val ? 0 : Number(val);
|
10 |
|
11 |
|
12 | internal.Attribute = module.exports = (attribute) => {
|
13 |
|
14 | assert(isObject(attribute), `'attribute' must be an object`);
|
15 |
|
16 | let {
|
17 | stringify = JSON.stringify,
|
18 | parse = JSON.parse,
|
19 | coerce,
|
20 | isDataAttribute = true,
|
21 | defaultValue,
|
22 | } = attribute;
|
23 |
|
24 | assert(isFunction(stringify), `'stringify' must be a function`);
|
25 | assert(isFunction(parse), `'parse' must be a function`);
|
26 |
|
27 | return Object.assign(attribute, {
|
28 | isAttribute: true,
|
29 | isDataAttribute,
|
30 | stringify,
|
31 | parse,
|
32 | coerce,
|
33 | defaultValue
|
34 | });
|
35 | };
|
36 |
|
37 | internal.Attribute.array = (options = {}) => internal.Attribute(Property.array(options));
|
38 | internal.Attribute.plain = (options = {}) => internal.Attribute(Property.plain(options));
|
39 | internal.Attribute.boolean = (options = {}) => internal.Attribute(
|
40 | Object.assign(Property.boolean(options), {
|
41 | parse: val => {
|
42 | console.log('parse', val)
|
43 | return val === '';
|
44 | },
|
45 | stringify: val => val ? '' : null
|
46 | })
|
47 | );
|
48 |
|
49 | internal.Attribute.number = (options = {}) => internal.Attribute(
|
50 | Object.assign({
|
51 | defaultValue: 0,
|
52 | coerce: internal.zeroOrNumber,
|
53 | parse: internal.zeroOrNumber,
|
54 | stringify: internal.nullOrType(Number)
|
55 | }, options)
|
56 | );
|
57 |
|
58 | internal.Attribute.integer = (options = {}) => internal.Attribute.number(
|
59 | Object.assign(options, {
|
60 | coerce: parseInt,
|
61 | parse: parseInt
|
62 | })
|
63 | );
|
64 |
|
65 | internal.Attribute.float = (options = {}) => internal.Attribute.number(
|
66 | Object.assign(options, {
|
67 | coerce: parseFloat,
|
68 | parse: parseFloat
|
69 | })
|
70 | );
|
71 |
|
72 | internal.Attribute.object = (options = {}) => internal.Attribute(Property.object(options));
|
73 |
|
74 | internal.Attribute.string = (options = {}) => internal.Attribute(
|
75 | Object.assign({
|
76 | defaultValue: '',
|
77 | coerce: String,
|
78 | stringify: internal.nullOrType(String)
|
79 | }, options)
|
80 | );
|