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. 返されるヘッダー リンクのコピーリンクがクリップボードにコピーされました!
headers プロパティーを return オブジェクトに追加して応答ヘッダーを設定できます。これらのヘッダーは抽出され、呼び出し元に応答して送信されます。
応答ヘッダーの例
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;
}
}