All files / websocket disconnect.js

100% Statements 9/9
100% Branches 0/0
100% Functions 1/1
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31                    1x 1x   1x 1x   1x 2x 2x             1x     2x    
/**
 * WebSocket $disconnect route — best-effort cleanup of the connection row
 * written by connect.js. API Gateway does not guarantee this route always
 * fires (a crashed tab, a network partition), which is why
 * WebSocketConnectionsTable also has a TTL (`expiresAt`) as a backstop —
 * this handler is an optimization to prune promptly, not the only cleanup
 * path, so any failure here is logged and swallowed rather than surfaced as
 * a Lambda error.
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, DeleteCommand } = require('@aws-sdk/lib-dynamodb')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
exports.handler = async (event) => {
  try {
    await docClient.send(
      new DeleteCommand({
        TableName: process.env.WEBSOCKET_CONNECTIONS_TABLE_NAME,
        Key: { connectionId: event.requestContext.connectionId }
      })
    )
  } catch (error) {
    console.error('[websocket/disconnect] Exception:', error.message, error.stack)
  }
 
  return { statusCode: 200, body: 'Disconnected' }
}