parseSpecText function

ApiSpec parseSpecText(
  1. String text, {
  2. String source = '<spec>',
})

Parses spec text (JSON or YAML) into an ApiSpec.

Implementation

ApiSpec parseSpecText(String text, {String source = '<spec>'}) {
  final Object? decoded;
  try {
    decoded = text.trimLeft().startsWith('{')
        ? jsonDecode(text)
        : yamlToPlain(loadYaml(text));
  } on YamlException catch (e) {
    throw SpecException('Could not parse $source as YAML: ${e.message}');
  } on FormatException catch (e) {
    throw SpecException('Could not parse $source as JSON: ${e.message}');
  }
  if (decoded is! Map) {
    throw SpecException('$source is not an OpenAPI/Swagger object.');
  }
  try {
    return ApiSpec.fromDocument(
      decoded.map((k, v) => MapEntry(k.toString(), v)),
    );
  } on FormatException catch (e) {
    throw SpecException('$source: ${e.message}');
  }
}