1
0
mirror of https://github.com/openshift/openshift-docs.git synced 2026-02-05 21:46:22 +01:00
Files
openshift-docs/modules/serverless-nodejs-functions-context-objects.adoc
2022-08-04 14:38:35 +00:00

62 lines
2.3 KiB
Plaintext

// Module included in the following assemblies
//
// * serverless/functions/serverless-developing-nodejs-functions.adoc
:_content-type: REFERENCE
[id="serverless-nodejs-functions-context-objects_{context}"]
= Node.js context objects
Functions are invoked by providing a `context` object as the first parameter. This object provides access to the incoming HTTP request information.
.Example context object
[source,javascript]
----
function handle(context, data)
----
This information includes the HTTP request method, any query strings or headers sent with the request, the HTTP version, and the request body. Incoming requests that contain a `CloudEvent` attach the incoming instance of the CloudEvent to the context object so that it can be accessed by using `context.cloudevent`.
[id="serverless-nodejs-functions-context-objects-methods_{context}"]
== Context object methods
The `context` object has a single method, `cloudEventResponse()`, that accepts a data value and returns a CloudEvent.
In a Knative system, if a function deployed as a service is invoked by an event broker sending a CloudEvent, the broker examines the response. If the response is a CloudEvent, this event is handled by the broker.
.Example context object method
[source,javascript]
----
// Expects to receive a CloudEvent with customer data
function handle(context, customer) {
// process the customer
const processed = handle(customer);
return context.cloudEventResponse(customer)
.source('/handle')
.type('fn.process.customer')
.response();
}
----
[id="serverless-nodejs-functions-context-objects-cloudevent-data_{context}"]
== CloudEvent data
If the incoming request is a CloudEvent, any data associated with the CloudEvent is extracted from the event and provided as a second parameter. For example, if a CloudEvent is received that contains a JSON string in its data property that is similar to the following:
[source,json]
----
{
"customerId": "0123456",
"productId": "6543210"
}
----
When invoked, the second parameter to the function, after the `context` object, will be a JavaScript object that has `customerId` and `productId` properties.
.Example signature
[source,javascript]
----
function handle(context, data)
----
The `data` parameter in this example is a JavaScript object that contains the `customerId` and `productId` properties.