convert-mongodb-to-graphql
TypeScript icon, indicating that this package has built-in type declarations

1.1.6 • Public • Published

convert mongodb to graphql

Automatic GraphQL API generator for mongodb models.

Usage

convert mongodb to graphql automatically generates a GraphQL schema for [mongodb] The schema is created based on the mongodb Schema Models It creates a rich set of filter arguments for the relations and provides a simple way to add custom filters.

The following example creates a schema for the all models that exists in path /models and executes a GraphQL query:

const graphql = require('graphql').graphql;
import { GraphQlSchemaBuilder } from 'convert-mongodb-to-graphql';
var requireDir = require('require-dir');
var modulesPackage = requireDir('../models/MongoDBModels') as any[];
import { middlewareFunction } from "../models/MongoGraphSchema/graphMiddleWare";


// mongodb models.
   Object.values(modulesPackage).forEach((ele:any)=>{ 
      Object.values(ele).map(single_ele=>{
        models.push(single_ele) 
      })
    });  

  const schema = new GraphQlSchemaBuilder()  
  .generateModel(models)
  .extendWithMiddleware(middlewareFunction)
  .argFactory((fields: any, modelClass: any) => { 
    var args: { [key: string]: any } = {};
  

    _.forOwn(fields, (field: any, propName: any) => {
       args['Function'] = {
        // For our filter the type of the value needs to be  
        // the same as the type of the field.
        type: GraphQLString,
        query: (query: any, value: any) => {
          // console.log(value)
          return    query
          // query is an Mongo QueryBuilder instance.
        }
  
      }
              args['pages'] = {
            // For our filter the type of the value needs to be 
            // the same as the type of the field.
            type:new GraphQLList(GraphQLInt),
            
            query: (query:any, value:any) => {
                let page = value[0]
                let limit = value[1]
                let end = (+page + 1) * (+limit) - 1
                let start = (+page * +limit)
      
            return query.skip(start).limit(limit);
            }
          }
      args['Limit'] = { 
        // For our filter the type of the value needs to be 
        // the same as the type of the field.
        type: GraphQLInt,
        query: (query: any, limit: any) => {
      return    query.limit(limit)
     
        }
  
      }
     
  })
 


  return args

}).generateAllInOneSchema();



// Execute a GraphQL query.
graphql(graphQlSchema, `{
  movies(name_Like: "erminato", page: [0, 2], created_orderBy: 1) {
    name,
    releaseDate,
    
    actors(gender_Eq: Male, age_Lte: 100, FirstName_orderBy: 1) {
      id
      firstName,
      age
    }
    
    reviews(stars_In: [3, 4, 5]) {
      title,
      text,
      stars,
      
      reviewer {
        firstName
      }
    }
  }
}`).then(result => {
  console.log(result.data.movies);
});

The example query used some of the many default filter arguments. For example the nameLike: "%erminato%" filter is mapped into a where clause where name like 'erminato'. Similarily the ageLte: 100 is mapped into a where age <= 100 clause. In addition to the property filters there are some special arguments like orderBy and range. Check out this table for a full list of filter arguments available by default.

Getting started

If you are already using mongodb and graphql the example in the usage section is all you need to get started. .

Filters

argument type action
propـEq: value property type prop = value
prop_Ne: value property type prop = value
prop_Gt: value property type prop > value
prop_Gte: value property type prop >= value
prop_Lt: value property type prop < value
prop_Lte: value property type prop <= value
prop_Like: value string prop LIKE value
prop_In: value Array prop IN value
prop_NotIn: value Array prop NOT IN value
propـorderByDesc: value string Order the result by some property in descending order
propـorderBy: value string Order the result by some property

Special arguments

argument action
orderBy: prop Order the result by some property
orderByDesc: prop Order the result by some property in descending order
Limit: prop Select a given number of records.
page: prop paging the records [0,10].
Function: prop To handle Custom Funtions (Add - Edit - Delete).

Best wishes to all backend developers who love Node.js

author : Hossam Radwan

Readme

Keywords

Package Sidebar

Install

npm i convert-mongodb-to-graphql

Weekly Downloads

2

Version

1.1.6

License

ISC

Unpacked Size

33.4 kB

Total Files

9

Last publish

Collaborators

  • hossamxp33