postgraphile-json-validation-plugin
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

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.

Package Sidebar

Install

npm i postgraphile-json-validation-plugin

Weekly Downloads

0

Version

0.0.2

License

MIT

Unpacked Size

12.1 kB

Total Files

9

Last publish

Collaborators

  • scotti2scotti