Skip to content

Commit 3f760e5

Browse files
authored
Merge pull request #77513 from rh-max/srvls-nodejs-cloudevent-types
[SRVOCF-515] Add Node.js functions docs on arbitrary data types to the
2 parents 6349419 + 9b513b6 commit 3f760e5

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

modules/serverless-nodejs-functions-context-objects.adoc

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,64 @@ function handle(context, data)
5353
----
5454

5555
The `data` parameter in this example is a JavaScript object that contains the `customerId` and `productId` properties.
56+
57+
[id="serverless-nodejs-functions-context-objects-arbitrary-data_{context}"]
58+
== Arbitrary data
59+
60+
A function can receive any data, not just `CloudEvents`. For example, you might want to call a function by using POST with an arbitrary object in the body:
61+
62+
[source,json]
63+
----
64+
{
65+
"id": "12345",
66+
"contact": {
67+
"title": "Mr.",
68+
"firstname": "John",
69+
"lastname": "Smith"
70+
}
71+
}
72+
----
73+
74+
In this case, you can define the function as follows:
75+
76+
[source,javascript]
77+
----
78+
function handle(context, customer) {
79+
return "Hello " + customer.contact.title + " " + customer.contact.lastname;
80+
}
81+
----
82+
83+
Supplying the contact object to the function would then return the following output:
84+
85+
[source,text]
86+
----
87+
Hello Mr. Smith
88+
----
89+
90+
[id="serverless-nodejs-functions-context-objects-supported-data-types_{context}"]
91+
== Supported data types
92+
93+
CloudEvents can contain various data types, including JSON, XML, plain text, and binary data. These data types are provided to the function in their respective formats:
94+
95+
* *JSON Data*: Provided as a JavaScript object.
96+
* *XML Data*: Provided as an XML document.
97+
* *Plain Text*: Provided as a string.
98+
* *Binary Data*: Provided as a Buffer object.
99+
100+
[id="serverless-nodejs-functions-context-objects-multiple-data-types-in-a-function_{context}"]
101+
== Multiple data types in a function
102+
103+
Ensure your function can handle different data types by checking the Content-Type header and parsing the data accordingly. For example:
104+
105+
[source,javascript]
106+
----
107+
function handle(context, data) {
108+
if (context.headers['content-type'] === 'application/json') {
109+
// handle JSON data
110+
} else if (context.headers['content-type'] === 'application/xml') {
111+
// handle XML data
112+
} else {
113+
// handle other data types
114+
}
115+
}
116+
----

0 commit comments

Comments
 (0)