简体   繁体   English

Flutter restheart oid 映射

[英]Flutter restheart oid mapping

Using flutter dio and retrofit I run into problems with a restheart API.使用 flutter dio 和 retrofit 时,我遇到了休息心脏 API 的问题。

How does one properly map the mongodb oid?如何正确 map mongodb oid?

I've got a main.dart like this:我有一个 main.dart 像这样:

import 'dart:convert';
import 'package:dio/dio.dart';
import 'dart:developer';

import 'package:retrofit_experiment/utils/rest_client.dart';

var auth = 'Basic ' + base64Encode(utf8.encode('admin:secret'));

Future<void> main(List<String> args) async {
  final dio = Dio(); // Provide a dio instance
  dio.options.headers["authorization"] = auth;

  final client = RestClient(dio);

  final json = await client.getUser("61a94d306c573846b4c0f8bf");

  log(
    'User with id 61a94d306c573846b4c0f8bf',
    name: 'getUser',
    error: jsonEncode(json),
  );

  client.getUser("61a94d306c573846b4c0f8bf").then((it) => print(it.id));

}

a rest_client.dart:一个rest_client.dart:

import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';

import 'package:retrofit_experiment/model/user.dart';

part 'rest_client.g.dart';

@RestApi(baseUrl: "http://localhost:8080")
abstract class RestClient {
  factory RestClient(Dio dio, {String baseUrl}) = _RestClient;

  @GET("/users/{id}")
  Future<User> getUser(@Path("id") String id);
}

which generates:生成:

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'rest_client.dart';

// **************************************************************************
// RetrofitGenerator
// **************************************************************************

class _RestClient implements RestClient {
  _RestClient(this._dio, {this.baseUrl}) {
    baseUrl ??= 'http://localhost:8080';
  }

  final Dio _dio;

  String? baseUrl;

  @override
  Future<User> getUser(id) async {
    const _extra = <String, dynamic>{};
    final queryParameters = <String, dynamic>{};
    final _data = <String, dynamic>{};
    final _result = await _dio.fetch<Map<String, dynamic>>(_setStreamType<User>(
        Options(method: 'GET', headers: <String, dynamic>{}, extra: _extra)
            .compose(_dio.options, '/users/$id',
                queryParameters: queryParameters, data: _data)
            .copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl)));
    final value = User.fromJson(_result.data!);
    return value;
  }

  RequestOptions _setStreamType<T>(RequestOptions requestOptions) {
    if (T != dynamic &&
        !(requestOptions.responseType == ResponseType.bytes ||
            requestOptions.responseType == ResponseType.stream)) {
      if (T == String) {
        requestOptions.responseType = ResponseType.plain;
      } else {
        requestOptions.responseType = ResponseType.json;
      }
    }
    return requestOptions;
  }
}

and this user.dart:和这个用户。dart:

import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';

@JsonSerializable()
class User {
  @JsonKey(name: '_id.\$oid')
  String? id;
  @JsonKey(name: 'first_name')
  String? firstName;
  @JsonKey(name: 'last_name')
  String? lastName;
  String? avatar;
  String? email;

  User({this.id, this.firstName, this.lastName, this.avatar, this.email});

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

which generates:生成:

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

User _$UserFromJson(Map<String, dynamic> json) {
  return User(
    id: json[r'_id.$oid'] as String?,
    firstName: json['first_name'] as String?,
    lastName: json['last_name'] as String?,
    avatar: json['avatar'] as String?,
    email: json['email'] as String?,
  );
}

Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      r'_id.$oid': instance.id,
      'first_name': instance.firstName,
      'last_name': instance.lastName,
      'avatar': instance.avatar,
      'email': instance.email,
    };

I get the response data like this:我得到这样的响应数据:

{"_id.$oid":null,"first_name":"Emma","last_name":"…faces/3-image.jpg","email":"emma.wong@reqres.in"}

Everything gets properly mapped but not the oid.一切都得到正确映射,但不是 oid。 What am I doing wrong?我究竟做错了什么?

I'm not familiar with Dart, however I suspect the error is that you are trying to get the _id as a String where it is an ObjectId.我不熟悉 Dart,但是我怀疑错误是您试图将 _id 作为字符串获取,而它是 ObjectId。

RESTHeart represents the ObjectId using the so called strict mode RESTHeart 使用所谓的严格模式表示 ObjectId

{
 "_id": { "$oid": "61a94d306c573846b4c0f8bf" }
}

You might want to look at https://github.com/mongo-dart/mongo_dart/issues/145 to have an example on how to parse an ObjectId from its string representation.您可能想查看https://github.com/mongo-dart/mongo_dart/issues/145以获取有关如何从其字符串表示中解析 ObjectId 的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM