6.4. TypeScript 功能返回值
功能可以返回任何有效的 JavaScript 类型,或者没有返回值。当函数没有指定返回值且未指示失败时,调用者会收到 204 No Content 响应。
功能也可以返回 CloudEvent 或一个 Message 对象,以便将事件推送到 Knative Eventing 系统。在这种情况下,开发人员不需要了解或实施 CloudEvent 消息传递规范。使用响应提取并发送返回值中的标头和其他相关信息。
示例
export const handle: Invokable = function (
context: Context,
cloudevent?: CloudEvent
): Message {
// process customer and return a new CloudEvent
const customer = cloudevent.data;
return HTTP.binary(
new CloudEvent({
source: 'customer.processor',
type: 'customer.processed'
})
);
};
6.4.1. 返回的标头 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
您可以通过在 return 对象中添加 headers 属性来设置响应标头。这些标头会提取并发送至调用者。
响应标头示例
export function handle(context: Context, cloudevent?: CloudEvent): Record<string, any> {
// process customer and return custom headers
const customer = cloudevent.data as Record<string, any>;
return { headers: { 'customer-id': customer.id } };
}
6.4.2. 返回状态代码 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
您可以通过在返回对象中添加 statusCode 属性来设置 return 到调用者的状态代码:
状态代码示例
export function handle(context: Context, cloudevent?: CloudEvent): Record<string, any> {
// process customer
const customer = cloudevent.data as Record<string, any>;
if (customer.restricted) {
return {
statusCode: 451
}
}
// business logic, then
return {
statusCode: 240
}
}
也可以为函数创建和丢弃的错误设置状态代码:
错误状态代码示例
export function handle(context: Context, cloudevent?: CloudEvent): Record<string, string> {
// process customer
const customer = cloudevent.data as Record<string, any>;
if (customer.restricted) {
const err = new Error(‘Unavailable for legal reasons’);
err.statusCode = 451;
throw err;
}
}