Meteor-methods
提供:Dev Guides
流星-メソッド
Meteorメソッドは、サーバー側で記述された関数ですが、クライアント側から呼び出すことができます。
サーバー側では、2つの簡単なメソッドを作成します。 最初の引数は5を引数に追加し、2番目の引数は 10 を追加します。
メソッドを使用する
meteorApp.js
if(Meteor.isServer) {
Meteor.methods({
method1: function (arg) {
var result = arg + 5;
return result;
},
method2: function (arg) {
var result = arg + 10;
return result;
}
});
}
if(Meteor.isClient) {
var aaa = 'aaa'
Meteor.call('method1', aaa, function (error, result) {
if (error) {
console.log(error);
else {
console.log('Method 1 result is: ' + result);
}
}
);
Meteor.call('method2', 5, function (error, result) {
if (error) {
console.log(error);
} else {
console.log('Method 2 result is: ' + result);
}
});
}
アプリを起動すると、計算された値がコンソールに表示されます。
エラー処理
エラーを処理するには、 Meteor.Error メソッドを使用できます。 次の例は、ログインしていないユーザーのエラーを処理する方法を示しています。
if(Meteor.isServer) {
Meteor.methods({
method1: function (param) {
if (! this.userId) {
throw new Meteor.Error("logged-out",
"The user must be logged in to post a comment.");
}
return result;
}
});
}
if(Meteor.isClient) { Meteor.call('method1', 1, function (error, result) {
if (error && error.error === "logged-out") {
console.log("errorMessage:", "Please log in to post a comment.");
} else {
console.log('Method 1 result is: ' + result);
}});
}
コンソールには、カスタマイズされたエラーメッセージが表示されます。