swagger-api / apidom

Semantic parser for API specifications
https://swagger-api.github.io/apidom/
72 stars 18 forks source link

YAML KeyValuePair - Key can be any kind, not just scalar #130

Open char0n opened 4 years ago

char0n commented 4 years ago

Key in YAML can be represented by any kind - Scalar, Sequence and Mapping. As JavaScript doesn't allow that we have to do what other libraries do - convert the non-string Key into string key. We have three options for conversion:

1.) Using Symbol.toStringTag

using Object.prototype.toString to get a string representation of an object or an array.

js-yaml is using this approach.

---
? [ foo, bar ]
: - baz
? { foo: bar }
: - baz
  - baz

will become

{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] }

2.) Using Original YAML fragment

{[1, 2]: many}

will become

{ '[1, 2]': 'many' }

yaml library is using this approach as default behavior.

3.) Using Map Object for mapping

With new JavaScript Map type, any value (both objects and primitive values) may be used as either a key or a value.

That means that we can do the following:

{[1, 2]: many}

will become

Map{ [1, 2] => 'many' }

yaml library is using this approach as opt-in behavior with mapAsMap option.

Refs #1

webron commented 4 years ago

Not sure about AsyncAPI, but for OpenAPI this is not needed. From http://spec.openapis.org/oas/v3.0.3#format:

Keys used in YAML maps MUST be limited to a scalar string, as defined by the YAML Failsafe schema ruleset.

char0n commented 4 years ago

Yes both specifications doesn't allow that, but it doesn't change the situation. We have to be able represent this information on CST/AST level so that we could validate. Then we should be able to encode fields like that into ApiDOM so that one field defined like that doesn't stop us from generating full ApiDOM tree and possibly rendering it in editor view. Having fields defined in this way should trigger validation WARNING and not validation ERROR. This issue is about choosing strategy to use when situation like that happens.