Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

knative - 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);
})
question from:https://stackoverflow.com/questions/65854143/how-to-reply-with-a-cloudevent-using-cloudevents-sdk-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...