5

I not understand how correct reference to other schema. I used ajv, and have next two schema

First schema incorrect-email.json:

{
  "title": "Не корректный email",
  "properties": {
    "status": {
      "description": "Статус операции",
      "type": "integer",
      "enum": [68]
    },
    "error": {
      "$ref":"error.json"
    }
  },
  "required":["status", "error"],
  "additionalProperties": false
}

Second schema error.json:

{
  "type": "array",
  "minItems": 2,
  "items": {
    "type": "object",
    "properties": {
      "description_ru": {
        "description": "Информация об ошибке на русском языке",
        "type": "string"
      },
      "description_en": {
        "description": "Информация об ошибке на английском языке",
        "type": "string"
      }
    },
    "additionalProperties": false
  }
}

After run test i get this error

Error: can't resolve reference error.json from id # Mine validation method:

var valid = ajv.validate(require("../schema/login/incorrect-email.json"), data);

Me need reference to local schema error.json, not remote server and etc. Please tell me, where i can added id in this schemas and $ref for correct parse with ajv

Mihail Kuznetsov
  • 323
  • 5
  • 22
  • 1
    You need to assign `ids` to your ref. Read this https://github.com/epoberezkin/ajv/issues/47 and https://github.com/epoberezkin/ajv/issues/185 – pratikpawar Nov 08 '16 at 20:18

1 Answers1

4

Without changing schema files you can do:

ajv.addSchema(require('./incorrect-email.json', 'incorrect-email.json'));
ajv.addSchema(require('./error.json'), 'error.json');
var valid = ajv.validate('incorrect-email.json', data);

Instead of specifying schema IDs in addSchema calls you can specify ID attributes in schemas themselves (it is recommended). In any case Ajv, by default, will not use any IO to load schemas, schemas have to be preloaded with addSchema method. You can dynamically (and asynchronously) load schemas when you use compileAsync method, but you have to specify your loading mechanism yourself (can be anything - fs, http, etc.).

esp
  • 7,314
  • 6
  • 49
  • 79
  • Thanks you, it's work! One question, If the attachment is more than two, it turns out I have to write a handler to bypass all of embedded circuits? Sorry for my engliesh. – Mihail Kuznetsov Nov 09 '16 at 09:14
  • You can add all your schemas to the Ajv instance as long as they have different IDs – esp Nov 09 '16 at 09:57