gpt4 book ai didi

javascript - 当meteor方法抛出错误时如何刷新客户端值?

转载 作者:行者123 更新时间:2023-11-28 05:05:10 25 4
gpt4 key购买 nike

我编写了一个 Meteor 方法来更改对象。只有对象的所有者才能编辑属性。

该方法因此检查当前用户和对象所有者是否匹配。如果不匹配,该方法将引发异常并说明原因。

此方法有效,因为更改不会影响集合,并且错误对象会返回给客户端。

尽管如此,编辑后的属性不会更新以反射(reflect)其实际值。如何触发刷新值?

附加信息:我在前端使用 React;该对象没有在前端代码中显式更新(因此该方法似乎也在客户端运行)。

一些代码(简化,命名更改,明显的错误可能不在原始代码中;)

客户端:

  saveCommentChanges(updatedComment) {
Meteor.call('comment.updateComment', updatedComment, function (error, result) {
if (error && error.error === "not-authorized") {
Session.set("errorMessage", "You are only allowed to change own comments.");
}
});
}

服务器端:

if (Meteor.isServer) {  
Meteor.methods({
'comment.updateComment'(comment) {
check(comment, Object);

origComment = Comments.findOne(comment._id);

if (origComment.user != this.userId) {
console.log('user does not match');
throw new Meteor.Error('not-authorized');
}

let res = Comments.update(
{'_id': comment._id},
{$set: {date: comment.date,
comment: comment.comment}
}, {removeEmptyStrings: false});
}
}

最佳答案

更新后在客户端刷新:

  1. 确保在服务器上发布数据,然后添加到 Controller 中的构造函数 - this.subscribe('Comments');请参阅下面的 AngularJS 示例
  2. 服务器更新后,评论也应该更新。您可能还需要运行 meteor remove autopublish 以使前端正确更新。 meteor 服务器提示我这样做

在您的情况下,评论不会被过滤,您可以根据评论 ID 和用户过滤更新。如果没有找到已经存在的评论,那么更新将不起作用,您可以捕获抛出错误。

  if (Meteor.isServer) { 
// This code only runs on the server
Meteor.publish('comments', function publishComments() {
return Comments.find({});
});
}

Meteor.methods({
'comment.updateComment'(comment) {
check(comment, Object);

origComment = Comments.findOne(comment._id);

// option 1
if (origComment.user != this.userId) {
console.log('user does not match');
throw new Meteor.Error('not-authorized');
}

// keep the same update here

// option 2
let res = Comments.update(
{ '_id': comment._id,'user': origComment.user},
{$set: {date: comment.date,
comment: comment.comment}
}, {removeEmptyStrings: false});
return res;
}
);

imports/component/stocks/stocks.html

<button type="submit" class="btn btn-success btn-sm m-2" 
ng-hide="{{$ctrl.currentUser === null}}"
ng-click="$ctrl.buyStock(stock.name, 1)">
Buy 1 Share
</button>

imports/component/stocks/stocks.js

import angular from 'angular';
import angularMeteor from 'angular-meteor';
import template from './stocks.html';

import { Meteor } from 'meteor/meteor';
import { Stocks } from '../../api/Stocks.js';
import { UserStocks } from '../../api/UserStocks.js';

class StocksCtrl {

constructor($scope) {
$scope.viewModel(this);

this.subscribe('stocks');
this.subscribe('userStocks');

// Return the data mostly right now
this.helpers({
currentUser() {
return Meteor.user();
},
stocks() {
const selector = {};
// Show newest tasks at the top
return Stocks.find(selector, {
sort: {
name: 1
}
});
},
userStocks() {
return UserStocks.find({});
}
})
}

buyStock(stock, amt) {
console.log("Buying stock processing...");

// ADD TO UserStock
Meteor.call('userStocks.buy', stock, amt, function(error, result) {
if(error){
console.log(error.reason);
return;
}
// log to console
console.log("UserID: " + Meteor.userId() + "\n Username: " + Meteor.user().username
+ "\n Message: Purchase of " + amt + " shares of " + stock + " was successful.");

// alert the user
alert("Purchase of " + amt + " shares of " + stock + " was successful.");
});
console.log("Buying stock complete.");
}

}

export default angular.module('StocksApp', [
angularMeteor
])
.component('stocksApp', {
templateUrl: 'imports/components/stocks/stocks.html',
controller: ['$scope', StocksCtrl]
});

imports/api/UserStocks.js

import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';

export const UserStocks = new Mongo.Collection('userStocks');


if (Meteor.isServer) {
// This code only runs on the server
// Only publish tasks that are public or belong to the current user
Meteor.publish('userStocks', function getUserStocks() {
return UserStocks.find({
ownerID: { $eq: this.userId }
});
});
}

Meteor.methods({
'userStocks.buy' (stock, amount) {
// Make sure the user is logged in before inserting a task
if (!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}

// if currently exists, increase the amount by the amount purchased
// if it does not exit, the upsert true will create/insert
const newID = UserStocks.update(
{ ownerID: { $eq: this.userId }, stock: { $eq: stock } },
{ $setOnInsert: { ownerID: this.userId, stock: stock}, $inc: {amt: amount} },
{ upsert: true, returnNewDocument: true}
);

return newID;
}
});

服务器/main.js

import '../imports/api/Stocks.js';
import '../imports/api/UserStocks.js';

关于javascript - 当meteor方法抛出错误时如何刷新客户端值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41809257/

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