New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

db2graphql

Package Overview
Dependencies
Maintainers
1
Versions
57
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

db2graphql

Generate Graphql schema based on existing relational database

  • 0.3.15
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

db2graphql

Generates a Graphql schema and resolvers from an existing relational database

NPM Version Badge Build Status Badge Coverage Status Badge Dependencies Badge Module Size Badge Last Commit Badge

:exclamation::exclamation::exclamation: Warning: don't use this in production yet, but your feedback is very important!

Features

  • Fully compatible with express, koa, hapi and Apollo Server
  • Converts an existing relational database (only PostgreSQL for now) schema to a JSON schema
  • Generates a Graphql SDL schema with convenient types, queries and mutations
  • Implements a generic Graphql resolver ready for API prototyping
  • Load related records based on foreign keys
  • Allows to add/override resolvers

Demo

link to youtube video

Query example

query {
  getPageUsers(
    filter: "id#1,2,3"
    pagination: "limit=2;orderby=username desc"
    _debug: true
  ) {
    items {
      id
      username
      fullname(foo: "hello ")
      password
      posts(filter: "publish=true", _cache: false) {
        total
        items {
          title
          publish
          categories {
            title
          }
        }
      }
    }
  }
}

Limitations/TODO

  • Only PostgreSQL supported
  • Better database types handling
  • Better database queries optimization
  • Create tests
  • Create an NPM module
  • Move to TypeScript
  • Add more and improve convenient API methods. Currently, only:
    1. getPage
    2. getFirst
    3. putItem

Usage

Generate a Graphql schema from an existing relational database

const knex = require('knex');
const db2g = require('db2graphql');
const api = new db2g('demo', knex(require('./connection.json')));
await api.connect();
const schema = api.getSchema();

Example of file connection.json

{
  "client": "pg",
  "version": "10.6",
  "debug": false,
  "connection": {
    "host" : "127.0.0.1",
    "user" : "postgres",
    "password" : "postgres",
    "database" : "db2graphql"
  },
  "exclude": []
}

Complete example with Apollo Server

const knex = require('knex');
const db2g = require('db2graphql');
const { ApolloServer, gql } = require('apollo-server');

const start = async (cb) => {

  /**************************************/
  const api = new db2g('demo', knex(require('./connection.json')));
  await api.connect(); // Connects to database and extracts database schema

  // Set authorization hook example
  const validator = async (type, field, parent, args, context) => {
    return true; // Should return true/ false
  }
  const denied = async (type, field, parent, args, context) => {
    throw new Error('Access Denied'); // Denied callback
  }
  api.isAuthorized(validator, denied);

  // Example of adding extra field
  api.add('Users', 'fullname', 'String', (parent, args, context) => {
    return String(args.foo + parent.username);
  }, { foo: 'String' });

  // Example of overiding existing schema
  api.add('Users', 'password', 'String', () => '');

  // Get generated schema and resolvers
  const schema = api.getSchema();
  const resolvers = api.getResolvers();
  /**************************************/

  // Create Apollo Server and start
  if (!schema) throw new Error('Error: empty schema');
  console.log(schema);
  const server = new ApolloServer({
    typeDefs: gql`${schema}`,
    resolvers,
  });
  server.listen().then(({ url }) => {
    console.log(`🚀 Server ready at ${url}`);
  });
}

start();

Example without database connection

const db2g = require('db2graphql');
const api = new db2g('demo');

// Add a query and resolver
api.add('Query', 'getFoo', 'Boolean', async (root, args, context) => {
  return true;
}, { param: 'String!' });

// Ready to generate schema
const schema = api.getSchema();
const resolvers = api.getResolvers();

Run de demo

$ git clone https://github.com/taviroquai/db2graphql.git
$ cd db2graphql
$ npm install
$ psql -h localhost -U postgres -c "CREATE DATABASE db2graphql"
$ psql -h localhost -U postgres -f demo/database.sql db2graphql
$ cp demo/connection.example.json demo/connection.json
# Edit demo/connection.json
$ npm run start

Open browser on http://localhost:4000 and see your Graphql API ready!

Collab

Anyone is free to collab :)

License

MIT, what else?

Keywords

FAQs

Package last updated on 03 Mar 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc