How to reply with a CloudEvent using cloudevents sdk-javascript

884 views Asked by At

I want to use Knative Sequence to chain few ksvcs but failed. The first step ksvc can be triggered but not the rest of them.

In my ksvc(Node.js), I used CloudEvent js-sdk. I assume I would need to return a new CloudEvent after receiving it. So here comes my code:

app.post('/', (req, res)=>{ 
   const event = HTTP.toEvent({ headers: req.headers, body: req.body });

   // respond as an event
   const responseEventMessage = new CloudEvent({
      source: '/',
      type: 'event:response',
      ...event
    });
   responseEventMessage.data = {
      hello: 'world'
    };
    res.status(201).json(responseEventMessage);
})
2

There are 2 answers

1
Matej Vašek On BEST ANSWER

I believe HTTP.binary() or HTTP.structured() should be used to transform event to headers and body.

    const responseEventMessage = new CloudEvent({
        ...receivedEvent,
        source: '/',
        type: 'event:response'
    });
    // const message = HTTP.binary(responseEventMessage)
    const message = HTTP.structured(responseEventMessage)
    res.set(message.headers)
    res.send(message.body)

Edit: It might be required to set up body-parser.

const bodyParser = require('body-parser')
app.post("/", bodyParser.json(), (req, res) => {})

Also it's better to use cloneWith() instead of spreading.

    const responseEventMessage = receivedEvent.cloneWith({
        source: '/',
        type: 'event:response'
    });
0
Ville Aikas On

Hi there and sorry for the troubles.

I'm not very familiar with the js sdk, but the example we use here: https://github.com/knative/docs/blob/master/docs/serving/samples/cloudevents/cloudevents-nodejs/index.js#L64

uses .send() instead of .json()

As far as configuring the sequence, hopefully these examples help get the configuration of the sequence right: https://knative.dev/docs/eventing/flows/sequence/

Does the sequence Status show any errors?

And lastly, do you see any errors in the logs? Depending on which components you have installed this may vary, but if you're running the core and with InMemoryChannel the logs would be in knative-eventing namespace, and you'd see the imc-dispatcher-* pods which would provide a clue if the event is not constructed properly.