取决于“新创建的对象”是什么意思。如果是基于身份验证的应用程序,用户可以登录,您可以将评论的create_date 与一些用户的last_online 日期进行比较。如果不强制用户创建帐户,您可以将此类信息存储在本地存储或 cookie 中(当他/她上次访问该网站时)。
另一方面,如果您考虑实时更新 cmets 列表,我建议您使用 websockets 查看graphql-subscriptions。它使用pub-sub 机制为您提供用户界面的反应性。简单的用例 - 每当向帖子添加新评论时,都会通知每个用户/查看者,评论可以附加到 cmets 列表并以您想要的方式突出显示。
为了实现这一点,您可以创建一个名为newCommentAdded 的subscription,客户端将订阅它,并且每次创建新评论时,应用程序的server 端会通知(publish ) 关于那个。
这种情况的简单实现可能是这样的
const Subscription = new GraphQLObjectType({
name: 'Subscription',
fields: {
newCommentAdded: {
type: Comment, // this would be your GraphQLObject type for Comment
resolve: (root, args, context) => {
return root.comment;
}
}
}
});
// then create graphql schema with use of above defined subscription
const graphQLSchema = new GraphQLSchema({
query: Query, // your query object
mutation: Mutation, // your mutation object
subscription: Subscription
});
以上部分只是graphql-js部分,但是需要创建一个使用PubSub机制的SubscriptionManager。
import { SubscriptionManager, PubSub } from 'graphql-subscriptions';
const pubSub = new PubSub();
const subscriptionManagerOptions = {
schema: graphQLSchema,
setupFunctions: {
newCommentAdded: (options, args) => {
newCommentAdded: {
filter: ( payload ) => {
// return true -> means that the subscrition will be published to the client side in every single case you call the 'publish' method
// here you can provide some conditions when to publish the result, like IDs of currently logged in user to whom you would publish the newly created comment
return true;
}
}
},
pubsub: pubSub
});
const subscriptionManager = new SubscriptionManager(subscriptionManagerOptions);
export { subscriptionManager, pubSub };
最后一步是在必要时通过上面创建的SubscriptionManager 实例将publish 新创建的评论发送到客户端。您可以在创建新评论的突变方法中执行此操作,或者在您需要的任何地方执行此操作
// here newComment is your comment instance
subscriptionManager.publish( 'newCommentAdded', { comment: newComment } );
为了使用websockets 来制作pub-sub 机制,有必要在主服务器旁边创建这样一个服务器。您可以使用subscriptions-transport-ws 模块。
这种解决方案的最大优势在于它在您的应用程序中提供了反应性(实时更改应用于帖子下方的 cmets 列表等)。我希望这对于您的用例来说可能是一个不错的选择。