Search code examples
knativecloudeventsknative-eventing

How to reply with a CloudEvent using cloudevents sdk-javascript


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);
})

Solution

  • 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'
        });