programing

JSON 스키마에서 스키마를 확장하는 방법

linuxpc 2023. 3. 27. 21:03
반응형

JSON 스키마에서 스키마를 확장하는 방법

데이터 모델링에 JSON 스키마를 사용하고 있습니다.베이스를 정의합니다.Document스키마, 나중에 모델 스키마를 정의하는 데 사용합니다(예:Product,Category,User등).

모든 모델이 특정 구조/규칙을 상속받기를 원하기 때문에 이 작업을 수행합니다.예를 들어, 모든 모델인스턴스는 특정 공통 속성을 가져야 합니다(예:id,createdAt,updatedAtOOP 용어로는 다음과 같습니다.Product extends Document따라서 인스턴스 속성을 상속합니다.스키마 용어로 (내 생각에는)Document는 모델 스키마를 작성하기 위한 메타데이터입니다.

문서 스키마를 다음과 같이 정의했습니다.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "id": "http://example.com/schemas/document.json#",
  "title": "Document",
  "type": "object",
  "additionalProperties": false,
  "required": ["type", "name", "fields"],
  "properties": {
    "type": {
      "constant": "document"
    },
    "name": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "readOnly": {
      "type": "boolean"
    },
    "properties": {
      // common properties 
      // model-specific properties
    }
  }
}
  1. 초안의 모든 속성을 정의할 필요가 없도록 문서 메타 스키마가 기본 JSON 스키마(초안 07)를 "확장"하도록 지정하려면 어떻게 해야 합니까?$schema,id등?
  2. 이 명령어를 어떻게 지정할 수 있습니까?properties각 모델 스키마에는 몇 가지 공통 속성이 포함되어 있습니다.id,createdAt각 모델 스키마 정의에서 정의할 필요가 없습니다.

JSON Schema는 객체 지향 패러다임을 사용하지 않기 때문에 상속과 같은 개념이 잘 번역되지 않습니다.JSON Schema는 제약 조건의 집합입니다.그것은 대부분의 사람들이 익숙한 것처럼 가법적이기 보다는 감산적이다.즉, 빈 스키마가 지정되면 유효한 JSON 문서 집합은 모든 JSON 문서 집합입니다.키워드를 추가하면 유효한 JSON 문서 집합에서 제외됩니다.일단 세트에서 어떤 것을 제거하면 다시 추가할 수 없습니다.

따라서 컴포지션을 사용하여 스키마를 "확장"할 수 있지만 다른 스키마가 정의하는 것은 "덮어쓰기"할 수 없습니다.

경합하는 속성이 없는 단순한 확장 예를 살펴보겠습니다.

/syslog/base

{
  "type": "object",
  "properties": {
    "foo": { "type": "string" },
    "bar": { "type": "string" }
  }
}

/syslog/syslogs

{
  "allOf": [{ "$ref": "/schema/base" }],
  "properties": {
    "baz": { "type": "string" }
  }
}

이것은 JSON Schema와 함께 사용할 수 있습니다.이제 속성 정의가 충돌하는 예를 살펴보겠습니다.

/syslog/syslogs

{
  "allOf": [{ "$ref": "/schema/base" }],
  "properties": {
    "bar": { "type": "integer" },
    "baz": { "type": "boolean" }
  }
}

이 예에서는 두 스키마 모두/properties/bar만약 당신이 이것을 상속의 관점에서 생각한다면, 당신은 여기서 무슨 일이 일어나고 있는지 오해할 것이다. 경우 "/properties/bar" 필드는 모두 유효해야 합니다.해결할 경합은 없습니다.키워드에서 알 수 있듯이 "모든" 스키마가 유효해야 합니다.부터bar정수와 문자열은 둘 다일 수 없습니다. 어떤 문서도 에 대해 검증되지 않습니다./schema/override.

그것이 문제를 해결하고 가장 일반적인 문제를 피하기 위한 충분한 정보를 제공하기를 바랍니다.

NodeJs를 사용하는 경우 다음과 같은 ajv 검증기를 사용하여 간단한 코드를 가진 단순한 스키마에서 이러한 제한을 회피하는 것은 간단합니다.

function extendJsonSchema(baseSchema, extendingSchema) {
    let extendedSchema = Object.assign({}, extendingSchema);
    extendedSchema.properties = Object.assign(extendedSchema.properties, baseSchema.properties)
    extendedSchema.required = extendedSchema.required.concat(baseSchema.required)
    return extendedSchema
}


let baseSchema = require('./base.schema.json')
let extendingSchema = require('./extending.schema.json')

let extendedSchema = extendJsonSchema(baseSchema, extendingSchema)
const validate = ajv.compile(extendedSchema)

이것으로 적어도 제 사용 사례는 해결되었습니다.

언급URL : https://stackoverflow.com/questions/52566472/how-to-extend-a-schema-in-json-schema

반응형