5.4. Node.js 함수 반환 값
함수는 유효한 JavaScript 유형을 반환하거나 반환 값이 없을 수 있습니다. 함수에 반환 값이 지정되지 않고 실패가 표시되지 않으면 호출자는 204 No Content
응답을 받습니다.
또한 함수는 이벤트를 Knative Eventing 시스템으로 푸시하기 위해 CloudEvent 또는 Message
오브젝트를 반환할 수 있습니다. 이 경우 개발자는 CloudEvent 메시징 사양을 이해하고 구현할 필요가 없습니다. 반환된 값의 헤더 및 기타 관련 정보는 추출된 응답으로 전송됩니다.
예
function handle(context, customer) { // process customer and return a new CloudEvent return new CloudEvent({ source: 'customer.processor', type: 'customer.processed' }) }
5.4.1. 헤더 반환
return
오브젝트에 headers
속성을 추가하여 응답 헤더를 설정할 수 있습니다. 이러한 헤더는 추출된 호출에 대한 응답으로 전송됩니다.
응답 헤더의 예
function handle(context, customer) { // process customer and return custom headers // the response will be '204 No content' return { headers: { customerid: customer.id } }; }
5.4.2. 상태 코드 반환
statusCode
속성을 return
오브젝트에 추가하여 호출자에게 반환된 상태 코드를 설정할 수 있습니다.
상태 코드 예
function handle(context, customer) { // process customer if (customer.restricted) { return { statusCode: 451 } } }
상태 코드는 함수에서 생성되어 발생하는 오류에 대해 설정할 수 있습니다.
오류 상태 코드의 예
function handle(context, customer) { // process customer if (customer.restricted) { const err = new Error(‘Unavailable for legal reasons’); err.statusCode = 451; throw err; } }