SuitsDocs
레퍼런스노드 레퍼런스액션액션제어제어

코드

JavaScript 코드를 실행합니다.

개요

항목내용
카테고리제어
런타임JavaScript (Node.js)
출력return 값

설정 옵션

옵션설명필수
코드실행할 JavaScript 코드
타임아웃최대 실행 시간

입력 데이터 접근

// 트리거 데이터
const row = trigger.row;
const price = trigger.row.단가;
const quantity = trigger.row.수량;

// 이전 액션 결과
const queryResult = actions.query.rows;
const httpResponse = actions.http.response;

// 현재 시간
const now = new Date();

출력 (return)

// 단일 값
return total;

// 객체
return {
  totalPrice: total,
  taxIncluded: total * 1.1
};

// 배열
return filteredItems;

후속 액션에서 사용

{{actions.code.result}}              // return 값
{{actions.code.result.totalPrice}}   // 객체의 속성

활용 예시

계산

const price = trigger.row.단가;
const quantity = trigger.row.수량;
const discount = trigger.row.할인율 || 0;

const subtotal = price * quantity;
const discountAmount = subtotal * (discount / 100);
const total = subtotal - discountAmount;

return {
  subtotal,
  discountAmount,
  total,
  taxIncluded: total * 1.1
};

데이터 변환

// 배열 필터링
const activeItems = actions.query.rows.filter(row => row.status === 'active');

// 합계 계산
const total = actions.query.rows.reduce((sum, row) => sum + row.amount, 0);

// 그룹화
const byCategory = actions.query.rows.reduce((acc, row) => {
  const key = row.category;
  if (!acc[key]) acc[key] = [];
  acc[key].push(row);
  return acc;
}, {});

return { activeItems, total, byCategory };

문자열 처리

const name = trigger.row.이름;
const phone = trigger.row.전화번호;

// 전화번호 마스킹
const maskedPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');

// 이름에서 성 추출
const lastName = name.charAt(0);

return { maskedPhone, lastName };

날짜 계산

const dueDate = new Date(trigger.row.마감일);
const today = new Date();

// 날짜 차이 (일)
const diffTime = dueDate - today;
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

// D-day 형식
const dDay = diffDays > 0 ? `D-${diffDays}` : diffDays === 0 ? 'D-Day' : `D+${Math.abs(diffDays)}`;

return { diffDays, dDay, isOverdue: diffDays < 0 };

JSON 파싱

// 웹훅 데이터 파싱
const webhookData = trigger.body;

// 중첩 데이터 추출
const customerName = webhookData.order?.customer?.name || 'Unknown';
const items = webhookData.order?.items || [];
const totalAmount = items.reduce((sum, item) => sum + item.price * item.quantity, 0);

return { customerName, itemCount: items.length, totalAmount };

외부 API 응답 처리

const response = actions.http.response;

// 에러 체크
if (!response || response.error) {
  return { success: false, error: response?.error || 'Unknown error' };
}

// 필요한 데이터만 추출
const { id, status, created_at } = response.data;

return {
  success: true,
  orderId: id,
  orderStatus: status,
  createdAt: new Date(created_at).toLocaleDateString('ko-KR')
};

제한사항

보안과 성능을 위해 일부 기능이 제한됩니다.

항목제한
실행 시간최대 30초
메모리제한됨
외부 요청불가 (HTTP 액션 사용)
파일 시스템접근 불가

모범 사례

에러 처리

try {
  const result = someOperation();
  return { success: true, data: result };
} catch (error) {
  return { success: false, error: error.message };
}

null/undefined 체크

const value = trigger.row.optionalField ?? 'default';
const nested = trigger.body?.order?.customer?.name || 'Unknown';

가독성

복잡한 로직은 함수로 분리하세요.

function calculateDiscount(price, rate) {
  return price * (rate / 100);
}

function formatCurrency(amount) {
  return amount.toLocaleString('ko-KR') + '원';
}

const discount = calculateDiscount(trigger.row.price, trigger.row.discountRate);
return { discount: formatCurrency(discount) };