使用云函数时,来自 firestore 的时间戳被转换为地图

Me *_*Man 8 json timestamp flutter google-cloud-functions google-cloud-firestore

所以我有一个Timestampin cloud firestore。我正在使用云功能从 Firestore 检索数据以进行颤振。但是将JSON时间戳格式化为映射,因此我无法将其用作时间戳。如何再次将其转换为时间戳?
这就是我将时间戳添加到 firestore 的方式。

var reference = Firestore.instance.collection('posts');
      reference.add({
        'postTitle': this.title,
        'timestamp': DateTime.now(),
        'likes': {},
        'ownerId': userId,
      })
Run Code Online (Sandbox Code Playgroud)

要检索数据,这是代码:

 factory Post.fromJSON(Map data){
    return Post(
      timestamp: data['timestamp'],
    );
  }
Run Code Online (Sandbox Code Playgroud)
List<Post> _generateFeed(List<Map<String, dynamic>> feedData) {
    List<Post> listOfPosts = [];

    for (var postData in feedData) {
      listOfPosts.add(Post.fromJSON(postData));
    }

    return listOfPosts;
  }
Run Code Online (Sandbox Code Playgroud)

但这会返回错误。

I/flutter (17271): The following assertion was thrown building FutureBuilder<DocumentSnapshot>(dirty, state:
I/flutter (17271): _FutureBuilderState<DocumentSnapshot>#1536b):
I/flutter (17271): type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Timestamp'
Run Code Online (Sandbox Code Playgroud)

这是我的云功能。
getFeed.ts

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

export const getFeedModule = function(req, res){
    const uid = String(req.query.uid);

    async function compileFeedPost(){
        const following = await getFollowing(uid, res)as any;

        let listOfPosts = await getAllPosts(following, res);

        listOfPosts = [].concat.apply([], listOfPosts);

        res.send(listOfPosts);
    }

    compileFeedPost().then().catch();
}

async function getAllPosts(following, res) {
    let listOfPosts = [];

    for (let user in following){
        listOfPosts.push( await getUserPosts(following[user], res));
    }
    return listOfPosts;
}

function getUserPosts(userId, res){
    const posts = admin.firestore().collection("posts").where("ownerId", "==", userId).orderBy("timestamp")

    return posts.get()
    .then(function(querySnapshot){
        let listOfPosts = [];

        querySnapshot.forEach(function(doc){
            listOfPosts.push(doc.data());
        });

        return listOfPosts;
    })
}

function getFollowing(uid, res){
    const doc = admin.firestore().doc(`user/${uid}`)
    return doc.get().then(snapshot => {
        const followings = snapshot.data().followings;

        let following_list = [];

        for (const following in followings){
            if (followings[following] === true){
                following_list.push(following);
            }
        }
        return following_list;
    }).catch(error => {
        res.status(500).send(error)
    })
}
Run Code Online (Sandbox Code Playgroud)

云功能 index.ts

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { getFeedModule } from "./getFeed"
admin.initializeApp();

export const getFeed = functions.https.onRequest((req, res) => {
    getFeedModule(req, res);
})


Run Code Online (Sandbox Code Playgroud)

由此调用

I/flutter (17271): The following assertion was thrown building FutureBuilder<DocumentSnapshot>(dirty, state:
I/flutter (17271): _FutureBuilderState<DocumentSnapshot>#1536b):
I/flutter (17271): type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Timestamp'
Run Code Online (Sandbox Code Playgroud)

Ada*_*aka 9

您可以使用 Converted 来接收 DateTime,如下所示:

class TimestampConverter implements JsonConverter<DateTime, dynamic> {
  const TimestampConverter();

  @override
  DateTime fromJson(dynamic data) {
    Timestamp timestamp;
    if (data is Timestamp) {
      timestamp = data;
    } else if (data is Map) {
      timestamp = Timestamp(data['_seconds'], data['_nanoseconds']);
    }
    return timestamp?.toDate();
  }

  @override
  Map<String, dynamic> toJson(DateTime dateTime) {
    final timestamp = Timestamp.fromDate(dateTime);
    return {
      '_seconds': timestamp.seconds,
      '_nanoseconds': timestamp.nanoseconds,
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样标记模型的字段:

@TimestampConverter() DateTime createdAt
Run Code Online (Sandbox Code Playgroud)


Dou*_*son 8

如果您正在处理已序列化为具有秒和纳秒组件的对象的 Timestamp,则可以使用这些组件创建一个带有new Timestamp(seconds, nanoseconds).


And*_*eev 5

实际上,在使用 Cloud 函数时,时间戳会作为普通 Map 返回。但是如果您使用 Firebase SDK,它会返回Timestamp对象。我使用以下函数来处理这两种情况:

DateTime dateTimeFromTimestamp(dynamic val) {
  Timestamp timestamp;
  if (val is Timestamp) {
    timestamp = val;
  } else if (val is Map) {
    timestamp = Timestamp(val['_seconds'], val['_nanoseconds']);
  }
  if (timestamp != null) {
    return timestamp.toDate();
  } else {
    print('Unable to parse Timestamp from $val');
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

json_annotationlib完美配合:

  @JsonKey(
      fromJson: dateTimeFromTimestamp,
      toJson: dateTimeToTimestamp,
      nullable: true)
  final DateTime subscriptionExpiryDate;
Run Code Online (Sandbox Code Playgroud)