All files / tenants update.js

100% Statements 41/41
94.44% Branches 17/18
100% Functions 1/1
100% Lines 41/41

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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 1201x 1x   1x 1x   1x     1x               1x 12x   12x 12x 12x 12x   12x 1x               11x             10x 1x             9x     9x 1x               8x 8x 8x   8x 5x 5x 5x     8x 2x 2x     8x 2x 2x     8x 1x             7x 7x     7x                       6x           2x 2x              
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
 
const client = new DynamoDBClient({})
const ddb = DynamoDBDocumentClient.from(client)
 
const TENANTS_TABLE = process.env.TENANTS_TABLE_NAME
 
// CORS headers to include in all responses
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers':
    'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token',
  'Access-Control-Allow-Methods': 'OPTIONS,GET,PUT,POST,DELETE'
}
 
exports.handler = async (event) => {
  console.log('Update Tenant Event:', JSON.stringify(event, null, 2))
 
  try {
    const tenantId = event.pathParameters?.tenantId
    const userId = event.requestContext.authorizer.claims.sub
    const body = JSON.parse(event.body || '{}')
 
    if (!tenantId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Tenant ID is required' })
      }
    }
 
    // Fetch the tenant
    const getTenantResult = await ddb.send(
      new GetCommand({
        TableName: TENANTS_TABLE,
        Key: { id: tenantId }
      })
    )
 
    if (!getTenantResult.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Tenant not found' })
      }
    }
 
    const tenant = getTenantResult.Item
 
    // Only the owner can update the tenant
    if (tenant.ownerId !== userId) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Only the tenant owner can update it' })
      }
    }
 
    // Build update expression
    const updateExpressions = []
    const expressionAttributeNames = {}
    const expressionAttributeValues = {}
 
    if (body.name) {
      updateExpressions.push('#name = :name')
      expressionAttributeNames['#name'] = 'name'
      expressionAttributeValues[':name'] = body.name
    }
 
    if (body.defaultLanguage) {
      updateExpressions.push('defaultLanguage = :defaultLanguage')
      expressionAttributeValues[':defaultLanguage'] = body.defaultLanguage
    }
 
    if (body.enabledLanguages) {
      updateExpressions.push('enabledLanguages = :enabledLanguages')
      expressionAttributeValues[':enabledLanguages'] = body.enabledLanguages
    }
 
    if (updateExpressions.length === 0) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'No fields to update' })
      }
    }
 
    updateExpressions.push('updatedAt = :updatedAt')
    expressionAttributeValues[':updatedAt'] = new Date().toISOString()
 
    // Update the tenant
    const result = await ddb.send(
      new UpdateCommand({
        TableName: TENANTS_TABLE,
        Key: { id: tenantId },
        UpdateExpression: `SET ${updateExpressions.join(', ')}`,
        ExpressionAttributeNames:
          Object.keys(expressionAttributeNames).length > 0 ? expressionAttributeNames : undefined,
        ExpressionAttributeValues: expressionAttributeValues,
        ReturnValues: 'ALL_NEW'
      })
    )
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify(result.Attributes)
    }
  } catch (error) {
    console.error('Error updating tenant:', error)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to update tenant', details: error.message })
    }
  }
}