2011-11-18 1 views
32

commonjs-utils의 node.js + json-schema.js를 사용하여 JSON API의 유효성을 검사하려고합니다. 단일 검증은 쉽지만 서로 참조 할 수 있도록 여러 스키마 파일을 관리하는 올바른 방법을 찾지 못했습니다.여러 JSON 스키마 파일을 관리하는 방법은 무엇입니까?

두 개의 모델 & 두 개의 API가 있다고 가정합니다.

// book 
{ 
    "type": "object", 
    "properties": { 
     "title": { "type": "string" }, 
     "author": { "type": "string" } 
    } 
} 
// author 
{ 
    "type": "object", 
    "properties": { 
     "first_name": { "type": "string" }, 
     "last_name": { "type": "string" } 
    } 
} 
// authors API 
{ 
    "type": "array", 
    "items": { "$ref": "author" } 
} 
// books API: list of books written by same author 
{ 
    "type": "object", 
    "properties": { 
    "author": { "$ref": "author" } 
    "books": { "type": "array", "items": { "$ref": "book" } } 
    } 
} 

각 스키마는 별도의 파일로 나누어 온라인 상태 일 수 있습니까? 또는 아래처럼 단일 스키마 파일로 결합 할 수 있습니까? 가능하다면 로컬 스키마를 어떻게 참조 할 수 있습니까?

JSON 스키마에서
// single schema file { 
    "book": { ... }, 
    "author": { ... }, 
    "authors": { ... }, 
    "books": { ... } } 

답변

46

, 당신은 파일 당 스키마를 넣고 자신 (당신이 그들을 저장) URL 또는 id 태그와 큰 스키마를 사용하여 액세스 할 수 있습니다. 여기

는 하나 개의 큰 파일입니다 :

{ 
    "id": "#root", 
    "properties": { 
     "author": { 
      "id": "#author", 
      "properties": { 
       "first_name": { 
        "type": "string" 
       }, 
       "last_name": { 
        "type": "string" 
       } 
      }, 
      "type": "object" 
     }, 
     // author 
     "author_api": { 
      "id": "#author_api", 
      "items": { 
       "$ref": "author" 
      }, 
      "type": "array" 
     }, 
     // authors API 
     "book": { 
      "id": "#book", 
      "properties": { 
       "author": { 
        "type": "string" 
       }, 
       "title": { 
        "type": "string" 
       } 
      }, 
      "type": "object" 
     }, 
     // books API: list of books written by same author 
     "books_api": { 
      "id": "#books_api", 
      "properties": { 
       "author": { 
        "$ref": "author" 
       }, 
       "books": { 
        "items": { 
         "$ref": "book" 
        }, 
        "type": "array" 
       } 
      }, 
      "type": "object" 
     } 
    } 
} 

그런 다음 (AN id로 정의된다) 그 하위 스키마 중 하나에 유효성 검사기를 참조 할 수 있습니다. 스키마 외부에서

이 :

{ "$ref": "url://to/your/schema#root/properties/book" } 

이하는 것과 같습니다

{ "$ref": "url://to/your/schema#book" } 

중 & hellip; 내부에서, 이와 동등한이다 :

{ "$ref": "#root/properties/book" } 

또는이 (여전히 내부에서) :

{ "$ref": "#book" } 

자세한 내용은 내 answer here를 참조하십시오.

+0

node.js에 분리 된 스키마 파일을 사용하여 개체를 만드는 방법이 있습니까? – uzay95

+1

@ uzay95 스키마는 클래스가 아닙니다. 스키마는 객체의 구조를 정의하고 유효성을 검사하는 데 사용되며, 클래스는 객체를 초기화 한 후에 객체의 구조를 정의합니다. js 클래스가 필요하면 Typescript, AtScript 또는 ES6을 살펴보십시오. 또는 node.js에 포함 할 외부 파일 내에 모듈 또는 생성자 팩터 리 메서드를 넣기 만하면됩니다. –