createSchemaAsync static method

Future<JsonSchema> createSchemaAsync(
  1. dynamic schema, {
  2. SchemaVersion? schemaVersion,
  3. Uri? fetchedFromUri,
  4. RefProviderAsync? refProvider,
})

Create a schema from a JSON data.

This method is asynchronous to support automatic fetching of sub-JsonSchemas for items, properties, and sub-properties of the root schema.

If you want to create a JsonSchema synchronously, use createSchema. Note that for createSchema remote reference fetching is not supported.

The schema can either be a decoded JSON object (Only Map or bool per the spec), or alternatively, a String may be passed in and JSON decoding will be handled automatically.

Implementation

static Future<JsonSchema> createSchemaAsync(dynamic schema,
    {SchemaVersion? schemaVersion,
    Uri? fetchedFromUri,
    RefProviderAsync? refProvider}) {
  // Default to assuming the schema is already a decoded, primitive dart object.
  dynamic data = schema;

  /// JSON Schemas must be [bool]s or [Map]s, so if we encounter a [String], we're looking at encoded JSON.
  /// https://json-schema.org/latest/json-schema-core.html#rfc.section.4.3.1
  if (schema is String) {
    try {
      data = yaon.parse(schema);
    } catch (e) {
      throw ArgumentError(
          'String data provided to createSchemaAsync is not valid JSON.');
    }
  }

  /// Set the Schema version before doing anything else, since almost everything depends on it.
  final version = _getSchemaVersion(schemaVersion, data);

  if (data is Map) {
    return JsonSchema._fromRootMap(
            Map<String, dynamic>.from(data), schemaVersion,
            fetchedFromUri: fetchedFromUri, refProviderAsync: refProvider)
        ._thisCompleter
        .future;

    // Boolean schemas are only supported in draft 6 and later.
  } else if (data is bool && version == SchemaVersion.draft6) {
    return JsonSchema._fromRootBool(data, schemaVersion,
            fetchedFromUri: fetchedFromUri, refProviderAsync: refProvider)
        ._thisCompleter
        .future;
  }
  throw ArgumentError(
      'Data provided to createSchemaAsync is not valid: Data must be, or parse to a Map (or bool in draft6 or later). | $data');
}