All files / ribbons create.js

100% Statements 30/30
90% Branches 9/10
100% Functions 2/2
100% Lines 30/30

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              1x 1x 1x 1x 1x   1x 1x   1x           9x 9x 9x   9x 1x           8x 8x 2x     6x 1x           5x 5x 1x     4x 4x                 4x               3x             1x 9x 9x   1x 1x              
/**
 * Create Ribbon Lambda
 * POST /v1/platform-admin/ribbons
 *
 * Requires `isPlatformAdmin: true`.
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, PutCommand } = require('@aws-sdk/lib-dynamodb')
const crypto = require('crypto')
const { requirePlatformAdmin } = require('../utils/requirePlatformAdmin')
const { validateRibbonMessage, validateRibbonColor } = require('../utils/validateRibbon')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const corsHeaders = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
async function createRibbonHandler(event) {
  const userId = event.requestContext?.authorizer?.claims?.sub
  const body = JSON.parse(event.body || '{}')
  const { message, color, active } = body
 
  if (message === undefined) {
    return {
      statusCode: 400,
      headers: corsHeaders,
      body: JSON.stringify({ error: 'Message is required' })
    }
  }
  const messageError = validateRibbonMessage(message)
  if (messageError) {
    return { statusCode: 400, headers: corsHeaders, body: JSON.stringify({ error: messageError }) }
  }
 
  if (color === undefined) {
    return {
      statusCode: 400,
      headers: corsHeaders,
      body: JSON.stringify({ error: 'Color is required' })
    }
  }
  const colorError = validateRibbonColor(color)
  if (colorError) {
    return { statusCode: 400, headers: corsHeaders, body: JSON.stringify({ error: colorError }) }
  }
 
  const now = new Date().toISOString()
  const ribbon = {
    id: crypto.randomUUID(),
    message,
    color,
    active: active !== false,
    createdAt: now,
    createdBy: userId
  }
 
  await docClient.send(
    new PutCommand({
      TableName: process.env.RIBBONS_TABLE_NAME,
      Item: ribbon,
      ConditionExpression: 'attribute_not_exists(id)'
    })
  )
 
  return {
    statusCode: 201,
    headers: corsHeaders,
    body: JSON.stringify(ribbon)
  }
}
 
exports.handler = requirePlatformAdmin(async (event) => {
  try {
    return await createRibbonHandler(event)
  } catch (error) {
    console.error('Error creating ribbon:', error)
    return {
      statusCode: 500,
      headers: corsHeaders,
      body: JSON.stringify({ error: 'Failed to create ribbon' })
    }
  }
})