본문 바로가기
C.W.K.
Stream
Lesson 07 of 08 · published

$ref 와 $defs — 재사용 가능한 조각

~12 min · json-schema, ref, defs, reuse

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

Schema 는 자라기 마련이고, 재사용이 그걸 감당하게 해준다

$defs — 로컬 정의

$defs 는 이름 붙인 sub-schema 를 모아두는 최상위 사전이야. 모양을 한 번만 정의해두고, 같은 문서 어디서든 $ref 로 불러다 써. Draft-07 시절의 definitions 키워드를 대신하는 자리야.

$ref — schema 포인터

$ref 는 URI Reference 를 받아. 같은 문서 안을 가리킬 땐 JSON Pointer 조각을 써 (#/$defs/Address). 다른 문서를 가리킬 땐 전체 URL 을 적고 (https://example.com/address.schema.json). validator 는 보통 외부 참조를 HTTP 로 받아와서 캐시하거나, '검증 전에 이 schema 들을 먼저 등록해라' 는 API 를 따로 제공해.

$id — 서로 참조하는 schema

schema 문서마다 잘 안 바뀌는 $id URL 을 하나 달아. 다른 schema 들이 그 주소를 보고 찾아와. validator 가 할 일은 그 $id 들을 일관되게 풀어주는 거야. 검증하기 전에 필요한 schema 를 전부 validator 에 올려두면 교차 참조는 알아서 굴러가.

원칙: schema 도 결국 JSON 이야. 코드처럼 다뤄. 반복되는 모양은 $defs 로 빼내고, 이름을 제대로 붙이고, $ref 로 돌려 써. address 객체가 세 번 복붙돼 있는 50 줄짜리 schema 는 리팩토링하라는 냄새야.

Code

한 문서의 $defs + $ref·json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id":     "https://example.com/order.schema.json",
  "type":    "object",
  "properties": {
    "billing_address":  { "$ref": "#/$defs/Address" },
    "shipping_address": { "$ref": "#/$defs/Address" }
  },
  "required": ["billing_address"],
  "$defs": {
    "Address": {
      "type": "object",
      "properties": {
        "street":      { "type": "string" },
        "city":        { "type": "string" },
        "postal_code": { "type": "string" }
      },
      "required": ["street", "city", "postal_code"]
    }
  }
}
교차 문서 $ref·json
{
  "$id":    "https://example.com/user.schema.json",
  "type":   "object",
  "properties": {
    "address": { "$ref": "https://example.com/address.schema.json" }
  }
}
검증 전 schema 로드 (ajv 예시)·javascript
import Ajv from 'ajv/dist/2020.js';

const ajv = new Ajv();
ajv.addSchema(addressSchema);  // $id: .../address.schema.json
ajv.addSchema(userSchema);     // $id 로 address 참조

const validate = ajv.getSchema('https://example.com/user.schema.json');
const valid = validate(data);

External links

Exercise

직접 쓴 실제 schema 를 하나 골라. OpenAPI 의 한 덩어리도 좋아. 두 번 넘게 반복되는 모양을 찾아서 $defs/Name 으로 빼내고, 중복된 자리는 $ref 로 갈아끼워. 그래도 schema 가 잘 도는지 검증해. 그 diff 가 $defs 가 왜 있는지에 대한 답이야.

Progress

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

댓글 0

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

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