0.0.2 • Published 5 years ago

postgraphile-json-validation-plugin v0.0.2

Weekly downloads
10
License
MIT
Repository
github
Last release
5 years ago

PostGraphile Json Validation Plugin

Package on npm MIT license

Minimal Json Validation plugin for PostGraphile

Use JSON Schema to validate CRUD operations on JSON/JSONB columns.

Usage

npm install postgraphile-json-validation-plugin

Having this table definition:

CREATE TABLE public.document (
  id SERIAL PRIMARY KEY,
  meta JSONB NOT NULL
);

and this schema:

{
  $id: 'http://example.s2s.com/foobar',
  type: 'object',
  properties: {
    foo: { type: 'integer' },
    bar: { type: 'string' },
  }
}

then you could use the plugin as follows:

import { Pool } from 'pg'
import { postgraphile, HttpRequestHandler } from 'postgraphile'
import { JsonValidationPlugin, Validation } from 'postgraphile-json-validation-plugin'

const middleware = (pool: Pool): HttpRequestHandler => {
  const validation = new Validation()
  const validate = validation.addSchema('document', 'meta', metaSchema)
  const plugin = JsonValidationPlugin(validate)
  return postgraphile(pool, 'public', {
    appendPlugins: [plugin],
    dynamicJson: true,
  })
}

Then This create mutation:

mutation {
  createDocument(input: {document: {id: 1, meta: {foo: "1", bar: 1}}}) {
    document {
      id
      meta
    }
  }
}

will fail with

{
  "errors": [
    {
      "message": "foo should be integer, bar should be string",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": ["createDocument"]
    }
  ],
  "data": {
    "createDocument": null
  }
}

But this one

mutation {
  createDocument(input: {document: {id: 1, meta: {foo: 1, bar: "1"}}}) {
    document {
      id
      meta
    }
  }
}

will succeed with

{
  "data": {
    "createDocument": {
      "document": {
        "id": 1,
        "meta": {
          "bar": "1",
          "foo": 1
        }
      }
    }
  }
}

Requirements

https://github.com/graphile/postgraphile#requirements

Thanks

Benjie Gillam for his awesome job.