OpenApi.fromString constructor

OpenApi.fromString({
  1. required String source,
  2. required OpenApiFormat? format,
})

Create an OpenApi object from a JSON/YAML string The format will be inferred from the file extension When the format is not provided, we will try both JSON and YAML

Implementation

factory OpenApi.fromString({
  required String source,
  required OpenApiFormat? format,
}) {
  Map<String, dynamic> parseJson(String source) {
    return json.decode(source);
  }

  Map<String, dynamic> parseYaml(String source) {
    final yamlMap = yaml.loadYaml(source);
    // We must set all keys to strings to avoid issues with the json encoder
    return json.decode(json.encode(
      yamlMap,
      toEncodable: (object) {
        // This item is most likely a map with a key that is not a string
        if (object is Map) {
          return object.map((k, v) => MapEntry(k.toString(), v));
        }
        return object.toJson();
      },
    ));
  }

  Map<String, dynamic> raw;
  if (format == OpenApiFormat.json) {
    raw = parseJson(source);
  } else if (format == OpenApiFormat.yaml) {
    raw = parseYaml(source);
  } else {
    try {
      raw = parseJson(source);
    } catch (e) {
      try {
        raw = parseYaml(source);
      } catch (e) {
        throw Exception('Could not parse the source as JSON or YAML');
      }
    }
  }
  return OpenApi.fromJson(raw);
}