如果您在不同的服务中,那么您需要使用公共 URL,并将您要调用的 API 标记为您提到的“管理员”访问权限。
如果您想在同一服务中从表脚本调用自定义 API,那么您只需“要求”自定义 API 并将其作为常规 JS 函数调用即可。请注意,尽管 API 采用“请求”和“响应”参数,但这是 JavaScript,因此任何看起来像请求/响应的东西都可以工作(鸭子类型)。例如,如果我将这个名为“计算器”的自定义 API 定义如下:
exports.post = function(request, response) {
var x = request.body.x || request.param('x');
var y = request.body.y || request.param('y');
var op = request.body.op || request.body.operation || request.param('op');
calculateAndReturn(x, y, op, response);
};
exports.get = function(request, response) {
var x = request.param('x');
var y = request.param('y');
var op = request.param('op') || request.param('operator');
calculateAndReturn(x, y, op);
};
function calculateAndReturn(x, y, operator, response) {
var result = calculate(x, y, operator);
if (typeof result === 'undefined') {
response.send(400, { error: 'Invalid or missing parameters' });
} else {
response.send(statusCodes.OK, { result : result });
}
}
function calculate(x, y, operator) {
var undef = {}.a;
if (_isUndefined(x) || _isUndefined(y) || _isUndefined(operator)) {
return undef;
}
switch (operator) {
case '+':
case 'add':
return x + y;
case '-':
case 'sub':
return x - y;
case '*':
case 'mul':
return x * y;
case '/':
case 'div':
return x / y;
}
return undef;
}
function _isUndefined(x) {
return typeof x === 'undefined';
}
请注意,对于 POST 操作,它只需要从请求中获取一个包含三个成员(x、y、op)的“body”参数,并且响应中调用的唯一函数是send。我们可以通过将它需要的内容传递给计算器来从表格脚本中调用它:
function insert(item, user, request) {
var calculator = require('../api/calculator');
var quantity = item.quantity;
var unitPrice = item.unitPrice;
calculator.post({ body: { x: quantity, y: unitPrice, op: '*' } }, {
send: function(status, body) {
if (status === statusCodes.OK) {
item.totalPrice = body.result;
request.execute();
} else {
request.respond(status, body);
}
}
});
}