Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions docs/serving/samples/cloudevents/cloudevents-nodejs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const { CloudEvent, Emitter, HTTP } = require('cloudevents')
const PORT = process.env.PORT || 8080
const target = process.env.K_SINK
const app = express()
const axios = require('axios').default;

const main = () => {
app.listen(PORT, function () {
Expand All @@ -36,42 +37,41 @@ const handle = (data) => {
// receiveAndSend responds with ack, and send a new event forward
const receiveAndSend = (cloudEvent, res) => {
const data = handle(cloudEvent.data)
const newCloudEvent = new CloudEvent({
const ce = new CloudEvent({
type: 'dev.knative.docs.sample',
source: 'https://github.com/knative/docs/docs/serving/samples/cloudevents/cloudevents-nodejs',
time: new Date(),
data
})

// With only an endpoint URL, this creates a v1 emitter
const emitter = new Emitter({
url: target
})
const message = HTTP.binary(ce); // Or HTTP.structured(ce))

// Reply back to dispatcher/client as soon as possible
res.status(202).end()

// Send the new Event to the K_SINK
emitter.send(newCloudEvent)
.then((res) => {
console.log(`Sent event: ${JSON.stringify(newCloudEvent, null, 2)}`)
console.log(`K_SINK responded: ${JSON.stringify({ status: res.status, headers: res.headers, data: res.data }, null, 2)}`)
})
.catch(console.error)
axios({
method: 'post',
url: target,
data: message.body,
headers: message.headers,
})
.then((responseSink) => {
console.log(`Sent event: ${JSON.stringify(ce, null, 2)}`)
console.log(`K_SINK responded: ${JSON.stringify({ status: responseSink.status, headers: responseSink.headers, data: responseSink.data }, null, 2)}`)
})
.catch(console.error)

}

// receiveAndReply responds with new event
const receiveAndReply = (cloudEvent, res) => {
const data = handle(cloudEvent.data)
const newCloudEvent = new CloudEvent({
const ce = new CloudEvent({
type: 'dev.knative.docs.sample',
source: 'https://github.com/knative/docs/docs/serving/samples/cloudevents/cloudevents-nodejs',
time: new Date(),
data
})

console.log(`Reply event: ${JSON.stringify(newCloudEvent, null, 2)}`)
const message = HTTP.binary(newCloudEvent);
console.log(`Reply event: ${JSON.stringify(ce, null, 2)}`)
const message = HTTP.binary(ce);
res.set(message.headers)
res.status(200).send(message.body)
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"author": "",
"license": "Apache-2.0",
"dependencies": {
"axios": "^0.21.1",
"cloudevents": "^4.0.0",
"express": "^4.17.1",
"nodemon": "^2.0.4"
Expand Down