gpt4 book ai didi

json - 使用云函数时,来自 firestore 的时间戳被转换为 Map

转载 作者:IT王子 更新时间:2023-10-29 06:53:10 27 4
gpt4 key购买 nike

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

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

要检索数据,这是代码:

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

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

return listOfPosts;
}

但这会返回一个错误。

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'

这是我的云函数。
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)
})
}

云函数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);
})


由此调用

_getFeed() async {
print("Starting getFeed");
FirebaseUser user = await FirebaseAuth.instance.currentUser();

SharedPreferences prefs = await SharedPreferences.getInstance();

String userId = user.uid;
var url =
'https://us-central1-jaluk-quiz.cloudfunctions.net/getFeed?uid=' + userId;
var httpClient = HttpClient();

List<QuizViewer>listOfPosts;
String result;
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == HttpStatus.ok) {
String json = await response.transform(utf8.decoder).join();
prefs.setString("feed", json);
List<Map<String, dynamic>> data =
jsonDecode(json).cast<Map<String, dynamic>>();
listOfPosts = _generateFeed(data);
result = "Success in http request for feed";
} else {
result =
'Error getting a feed: Http status ${response.statusCode} | userId $userId';
}
} catch (exception) {
result = 'Failed invoking the getFeed function. Exception: $exception';
}
print(result);

setState(() {
feedData = listOfPosts;
});
}

最佳答案

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

关于json - 使用云函数时,来自 firestore 的时间戳被转换为 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56245156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com