C.W.K.
Stream
Lesson 06 of 08 · published

조합 — allOf, oneOf, anyOf, not

~12 min · json-schema, composition, polymorphism

Level 0평문
0 XP0/64 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete

실세계 모양 모델링하기 위한 schema 조합

allOf — 교집합

인스턴스가 모든 sub-schema 검증해야 함. 상속 같은 조합에 사용: 'Base 이고 + 이 추가 필드 가짐'.

anyOf — 합집합 (최소 하나)

인스턴스가 최소 하나 sub-schema 검증해야 함. 모호/느슨한 합집합에 사용: 'string 또는 number', '여러 옵션 모양 중 하나'.

oneOf — 배타적 합집합 (정확히 하나)

인스턴스가 정확히 하나 sub-schema 검증해야 함. tagged union 에 사용: '신용카드 details 가진 결제 OR 은행이체 details 가진 결제, 둘 다 아님'.

not — 부정

인스턴스가 sub-schema 검증 안 해야 함. 아껴 사용 — not 의 에러 메시지 악명 높게 모호. 가능하면 긍정적으로 표현.

Tagged-union 패턴: 다형 데이터 ('N 변형 중 하나') 는 const 로 검증되는 식별 필드 (kind, type) 가진 oneOf 선호. validator 가 한 변형 매칭 시 명확한 에러 메시지; anyOf 는 사용자가 의도한 변형 모호하게 함.

Code

allOf — 추가 사항 가진 base 조합·json
{
  "$defs": {
    "Identifiable": {
      "type": "object",
      "properties": { "id": { "type": "integer" } },
      "required": ["id"]
    }
  },
  "allOf": [
    { "$ref": "#/$defs/Identifiable" },
    {
      "type": "object",
      "properties": {
        "name": { "type": "string" }
      },
      "required": ["name"]
    }
  ]
}
oneOf — tagged union (깨끗한 에러)·json
{
  "oneOf": [
    {
      "type": "object",
      "properties": {
        "kind":       { "const": "credit_card" },
        "card_last4": { "type": "string", "pattern": "^[0-9]{4}$" }
      },
      "required": ["kind", "card_last4"]
    },
    {
      "type": "object",
      "properties": {
        "kind":          { "const": "bank_transfer" },
        "routing_number": { "type": "string" },
        "account_last4":  { "type": "string", "pattern": "^[0-9]{4}$" }
      },
      "required": ["kind", "routing_number", "account_last4"]
    }
  ]
}
anyOf — string 또는 string 형태 number·json
{
  "properties": {
    "id": {
      "anyOf": [
        { "type": "integer" },
        { "type": "string", "pattern": "^[0-9]+$" }
      ]
    }
  }
}

External links

Exercise

'결제 방식' 을 세 변형 (credit_card / bank_transfer / wallet) 가진 oneOf 로 모델링, 각각 자체 필수 필드 + 공유 kind discriminator. 각 종류 문서 하나씩 검증. 두 종류 필드 섞은 문서 작성하고 validator 가 거부하는 거 확인 (어느 가지도 정확히 매칭 안 됨).

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.