【问题标题】:Dart Client-Side Type Generic REST Api CallsDart 客户端类型通用 REST Api 调用
【发布时间】:2021-10-20 17:58:17
【问题描述】:

据我了解,可以使用 REST 方法通过 HTTP 调用和处理 CRUD 操作。我的目标是通过 [POST, GET, PUT, DELETE] 管理大约 5 个实体的 CRUD 事务。总的来说,即使我可以在辅助函数中重用一些样板,我也必须编写 20 个不同的原型。

我想减少泛型类型的代码量。这是我的想法:

abstract class RestResource
{
    int id;
    static String name = "";
    RestResource({required this.id});
    Map<String, dynamic> toJson() => throw UnimplementedError();
    factory RestResource.fromJson(Map<String, dynamic> json) => throw UnimplementedError();
}

class ActualResource extends ResourceRest
{
    final String additional;
    static String name = "resource";
    ActualResource({required this.additional, required int id}) : super(id: id);

    @override
    Map<String, dynamic> toJson() { 
        // return serialized 
    };

    @override
    factory RestResource.fromJson(Map<String, dynamic> json) { 
        // create object from json 
    };
}

// Example for GET request for a resource with an id ex: api/resource/1234
Future<Resource> fetch<Resource extends RestResource>(int id) async {
    Uri url = Uri.http('http://www.someurl.com/api/', Resource.name + id.toString());
    http.Response res = await _httpClient.get(url);
    validateHTTPResponse(res);
    return Resource.fromJson(convert.jsonDecode(res.body));
}

// This is how I'd want to call it
int id = 1234;
ActualResource r = await fetch<ActualResource>(id);

我的问题。 Resource 是一个泛型类型,即使它扩展了 RestResource 的定义。调用工厂方法Resource.fromJson 会触发以下智能感知错误。

关于资源名称

The getter 'name' isn't defined for the type 'Type'.
Try importing the library that defines 'name', correcting the name to the name of an existing getter, or defining a getter or field named 'name'.

关于 Resource.fromJson

The method 'fromJson' isn't defined for the type 'Type'.
Try correcting the name to the name of an existing method, or defining a method named 'fromJson'

我想开始讨论开发人员如何做这样的事情,因为它可以节省大量的时间和精力。

【问题讨论】:

    标签: flutter rest http dart


    【解决方案1】:

    经过进一步研究,我发现我的方法目前不适用于 Dart w/Flutter,因为 dart:mirrors 仅在 VM 上可用。这是解决方案。我希望它能帮助其他 Flutter 开发者在编写 REST Api 客户端时减少样板文件的数量。感谢 Günter Zöchbauer 的回答:Dart Client-Side Type Generic REST Api Calls

    abstract class RestSerializable {
      RestSerializable.fromJson(); 
      Map<String, dynamic> toJson();
    }
    
    class ResourceA implements RestSerializable { // whatever you need + fromJson() + toJson() }
    
    class ResourceB implements RestSerializable { // whatever you need + fromJson() + toJson() }
    
    RestReource fromJson<RestReource extends RestSerializable>({required dynamic json}) {
      return jsonFactories[RestReource]!(json);
    }
    
    final jsonFactories = <Type, Function> {
      ResourceA : (Map<String, dynamic> json) => ResourceA.fromJson(json),
      ResourceB : (Map<String, dynamic> json) => ResourceB.fromJson(json),
    };
    
    final unencodedPathFactories = <Type, String> {
      ResourceA : "/api/resourceA/",
      ResourceB : "/api/resourceB/",
    };
    
    RestReource fromJson<RestReource extends RestSerializable>({required dynamic json}) {
      return jsonFactories[RestReource]!(json);
    }
    
    String unencodedPath<RestResource extends RestSerializable>() {
      return unencodedPathFactories[RestResource]!;
    }
    
    class RestApiClient {
      static const String AUTHORITY = "localhost:port";
      final http.Client _httpClient;
    
      // This is just one example.... You can add for POST, PUT, DELETE
      // GET Details
      Future<Resource> fetch<Resource extends RestSerializable>(int id) async {
        Uri url = Uri.http(AUTHORITY, unencodedPath<Resource>() + id.toString());
        http.Response res = await _httpClient.get(url);
        this.validateHTTPResponse(res, unencodedPath<Resource>());
        return fromJson<Resource>(json: convert.jsonDecode(res.body));
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      相关资源
      最近更新 更多