Skip to content

Commit

Permalink
Object field type
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Wolfe committed Oct 8, 2020
1 parent 3350ee4 commit 3098cab
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 1 deletion.
39 changes: 39 additions & 0 deletions lib/types/object.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const _ = require('lodash');
const normalize = require('../normalize');

const parse = function (string) {
if (string == null) { return string; }

let object;
if (_.isPlainObject(string)) {
object = _.cloneDeep(string);
} else if (_.isString(string)) {
// peek at the string to see if it looks like JSON
if (string.match(/^\s*{/)) {
object = parseObject(string);
}
}

object = object || { valid: false };
if (object.valid == null) { object.valid = true; }
object.raw = string.raw != null ? string.raw : string;
return object;
};

const parseObject = function (string) {
try {
return JSON.parse(string);
} catch (err) {
return { valid: false };
}
};

module.exports = {
parse,
components: [],
maskable: false,
operators: [],
examples: [
'{"property_1":"abc","property_2":"def"}'
].map(parse).map(normalize)
};
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

45 changes: 45 additions & 0 deletions test/object.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const { assert } = require('chai');
const object = require('../lib/types/object');

describe.only('Object', function () {
const objects = [
{foo: 'bar'},
'{"foo":"bar"}'
];

for (const val of objects) {
it(`should parse ${typeof val} ${JSON.stringify(val)} as object`, function () {
const parsed = object.parse(val);
assert.deepEqual(parsed.valueOf(), {foo: 'bar', valid: true, raw: val});
});
}

const invalids = [
' ',
'donkey',
'<foo>bar</foo>'
];

for (const val of invalids) {
it(`should parse ${typeof val} ${JSON.stringify(val)} as invalid`, function () {
const parsed = object.parse(val);
assert.deepEqual(parsed, {valid: false, raw: val});
});
}

it('should ignore whitespace', function () {
const val = ' {"foo":"bar"} ';
const parsed = object.parse(val);
assert.deepEqual(parsed.valueOf(), {foo: 'bar', valid: true, raw: val});
});

it('should handle parsing a parsed object', function () {
const val = '{"foo":"bar"}';
const parsed = object.parse(object.parse(val));
assert.deepEqual(parsed.valueOf(), {foo: 'bar', valid: true, raw: val});
});

it('should have examples', function () {
assert(object.examples.length);
});
});

0 comments on commit 3098cab

Please sign in to comment.