ajv-validator / ajv-merge-patch

$merge and $patch keywords for Ajv JSON-Schema validator to extend schemas
https://ajv.js.org
MIT License
46 stars 17 forks source link

Using $merge with Fastify and shared schemas #32

Closed PatrickHeneise closed 5 years ago

PatrickHeneise commented 5 years ago

I'm trying to put this together with fastify. I added ajv-merge-path as described in the docs into the validation (https://github.com/fastify/fastify/blob/master/lib/validation.js#L157)

example case:

schemas/defs.json

{
  "$id": "/defs.json",
  "type": "object",
  "definitions": {
    "test": {
      "type": "object",
      "properties": {
        "name": { "type": "string" }
      }
    }
  }
}

schemas/foo.json

{
  "$id": "/foo.json",
  "type": "object",
  "definitions": {
    "bar": {
      "type": "object",
      "$merge": {
        "source": {
          "$ref": "/defs.json#/definitions/test"
        },
        "with": {
          "properties": {
            "id": { "type": "string" }
          }
        }
      }
    }
  }
}
fastify.get('/defs.json', (request, reply) => {
  reply.send(require('./schemas/defs'))
})
fastify.get('/foo.json', (request, reply) => {
  reply.send(require('./schemas/foo'))
})
fastify.post(
  '/',
  {
    schema: {
      body: { $ref: '/foo.json#/definitions/bar' }
    }
  },
  function(request, reply) {
    reply.send(fastify.getSchemas())
  }
)

Any ideas how I can make this work?

epoberezkin commented 5 years ago

I think it should be submitted to fastify rather than here - most likely it simply doesn't support $merge. Also, fastify seems to use its own instance of ajv that doesn't have $merge added to it. Either fastify needs to add $merge to the instance or you need to pass your own instance (and it still doesn't mean $merge would work for anything but simple validation).

PatrickHeneise commented 5 years ago

Thanks, I'll check there.