AWS API Gateway Websocket UnknownError
are you trying to use postToConnection inside the connect handler? The websocket connection is only created after the connect handler has returned statusCode 200. You should not use postToConnection inside connect handler.
To avoid a 410 headache whilst employing websockets on serverless, don't forget to catch your exceptions:
export const ApiGatewayConnector = (event) => {
const endpoint = process.env.IS_OFFLINE
? 'http://localhost:3001'
: `${event.requestContext.domainName}/${event.requestContext.stage}`
const apiVersion = '2018-11-29'
return new AWS.ApiGatewayManagementApi({ apiVersion, endpoint })
}
....
if (event.requestContext.stage == 'local') {
await ApiGatewayConnector(event)
.postToConnection({ ConnectionId, Data })
.promise()
.catch(_ => removeId(ConnectionId));<----- N.B. Remove disconnected IDs
} else {
await ws.send(Data, ConnectionId)
}
}
That error is thrown when calling .postToConnection in answer to a $connect event. You can call .postConnection without errors in answer to a $default event.
// index.js
// the handler is defined as: index.handler
const AWS = require("aws-sdk");
exports.handler = function (event, context, callback) {
console.log('event.requestContext.eventType', event && event.requestContext && event.requestContext.eventType)
if (event.requestContext.eventType === "CONNECT") {
console.log('$connect event')
// calling apigwManagementApi.postToConnection will throw an exception
callback(null, {
statusCode: 200,
body: "Connected"
});
} else if (event.requestContext.eventType === "DISCONNECT") {
console.log('$disconnect event')
// calling apigwManagementApi.postToConnection is pointless since the client has disconneted
callback(null, {
statusCode: 200,
body: "Disconnected"
});
} else {
console.log('$default event')
const ConnectionId = event.requestContext.connectionId
const bodyString = event.body
const Data = bodyString
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: "2018-11-29",
endpoint: event.requestContext.domainName + "/" + event.requestContext.stage
});
apigwManagementApi
.postToConnection({ ConnectionId, Data })
.promise().then(() => {
callback(null, {
statusCode: 200,
body: "Disconnected"
});
})
}
};