When the client sends a websocket message to AWS websocket API Gateway the websocket Lambda handler function receives three arguments: event
, context
and callback
:
import type { APIGatewayProxyEvent, Context, } from "aws-lambda";
export class Handler {
constructor() {}
async execute(event: APIGatewayProxyEvent, context: Context, callback: any): Promise<void> {
console.log(`${event}, ${context}, ${callback}`);
if (!event.requestContext || !event.requestContext.connectionId) {
callback(null, { statusCode: 400, body: "Missing RequestContext" });
};
callback(null, {statusCode: 200, body: 'Your message was received'});
}
}
const Handler = new Handler(service);
async function handler(event: APIGatewayProxyEvent, context: Context, callback: any): Promise<void> {
return await Handler.execute(event, context, callback);
}
export default handler;
The Handler checks if the event
that it received contains the value for event.requestContext.connectionId
. If not, it calls the callback function passing null
as the first argument and a message containing the 400 statusCode
and body
with message telling that the connectionId is missing:
callback(null, { statusCode: 400, body: "Missing RequestContext" });
Unfortunately, I was not able to locate any AWS documentation describing how exactly we should be using this callback
function. Instead I've used some code examples found on Internet.
I was expecting that calling the callback
function passing it 400 status
will make the Handler function exit and raise an exception. But it doesn't happen. The handler just keeps going executing the next lines like nothing happened and callback function was never called.
- What is a real purpose for the
callback
function? - How do we return an error message from websocket Handler function letting the client application know about the occurred problem?
- How do we stop the Handler from executing the rest of the code if there was an exception or invalid parameter received?
- Should the websocket Handler return any value or should it be void - no value returned?
Please post your answer as a script example or as a snippet so we could test it.
P.S. The doc posted at https://aws.amazon.com/blogs/compute/announcing-websocket-apis-in-amazon-api-gateway/ says that:
The backend can send messages to specific users via a callback URL that is provided after the user is connected to the WebSocket API.
And there is a snippet showing it:
exports.handler = function(event, context, callback) {
var putParams = {
TableName: process.env.TABLE_NAME,
Item: {
connectionId: { S: event.requestContext.connectionId }
}
};
DDB.putItem(putParams, function(err, data) {
callback(null, {
statusCode: err ? 500 : 200,
body: err ? "Failed to connect: " + JSON.stringify(err) : "Connected"
});
});
};
from How to use AWS Websocket API Gateway Lambda endpoint callback function
No comments:
Post a Comment