instantiate<M extends MBaseModel> method

M instantiate<M extends MBaseModel>({
  1. dynamic json,
  2. MSchemaRef? type,
})

Implementation

M instantiate<M extends MBaseModel>({dynamic json, MSchemaRef? type}) {
  final Map<String, dynamic> map =
      (json as Map<String, dynamic>?) ?? <String, dynamic>{};
  final mtype = _typeExtractors.map((extract) => extract(map)).firstWhere(
      notNull(),
      orElse: () =>
          type?.toString() ??
          nullPointer<String>(
              "No mmodel type could be extracted from json payload.  Set either the mtype or mmeta/mtype properties"));

  final factory = lookupFactory(mtype!);
  if (factory == null && map.isNotEmpty) {
    if (M == MEntity || M == MModel || M == MBaseModel) {
      log.severe(
          "No mmodel type could be extracted from json payload.  Set either the mtype or mmeta/mtype properties");
      return DefaultMEntity(map) as M;
    } else {
      throw Exception(
          "No mmodel type could be extracted from json payload. Set either the mtype or mmeta/mtype properties");
    }
  }
  if (factory == null) {
    throw Exception("No factory was provided for type ${mtype}. "
        "Make sure you call register[Library]Models(mmodelRegistry, mEnumRegistry). ");
  } else {
    final generated = factory(map);
    if (generated is! M) {
      throw Exception(
          "Factory was found, but did not generate the correct type");
    }
    return generated;
  }
}