Giter VIP home page Giter VIP logo

graphql-sequelize-crud's Introduction

graphql-sequelize-crud

Automatically generate queries and mutations from Sequelize models

Build Status Maintainability Test Coverage

NPM


Demo
See demo/index.ts for demo source code.
The following is automatically generated from a simple Sequelize schema. graph Generated using graphql-viz.

Installation

# Install Peer Dependencies
npm install --save graphql graphql-relay graphql-sequelize-teselagen sequelize
# Install GraphQL-Sequelize-CRUD
npm install --save graphql-sequelize-crud

Usage

See demo/index.ts for demo source code.

Why

  • ✅ Less error prone development. No more keeping GraphQL in sync with Database fields.
  • Don't Repeat Yourself.
  • ✅ Power of GraphQL and Relay with rapid database development of Sequelize

Features

  • Generated GraphQL API only from Sequelize Models defintitions
    • Relay compatiable GraphQL API
  • Generate Queries
    • READ single
    • READ all
  • Generate Mutations
    • CREATE
    • UPDATE
    • DELETE
  • Custom queries and mutations within Sequelize Models defitions

graphql-sequelize-crud's People

Contributors

anat avatar daralthus avatar glavin001 avatar maxpain avatar mschinis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

graphql-sequelize-crud's Issues

Input Types can't define resolvers

Running the demo code is giving this error:

Unhandled rejection Error: createUserInput.id field type has a resolve property, but Input Types cannot define resolvers.
    at invariant (/home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/jsutils/invariant.js:19:11)
    at /home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/definition.js:657:31
    at Array.forEach (native)
    at GraphQLInputObjectType._defineFieldMap (/home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/definition.js:651:16)
    at GraphQLInputObjectType.getFields (/home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/definition.js:640:49)
    at /home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/schema.js:224:27
    at typeMapReducer (/home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/schema.js:229:7)
    at typeMapReducer (/home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/schema.js:187:12)
    at Array.reduce (native)
    at /home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/schema.js:215:38
    at Array.forEach (native)
    at /home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/schema.js:208:29
    at typeMapReducer (/home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/schema.js:219:7)
    at Array.reduce (native)
    at new GraphQLSchema (/home/prijindal/projects/Ideas/express/express-api/node_modules/graphql/type/schema.js:95:34)
    at getSchema (/home/prijindal/projects/Ideas/express/express-api/node_modules/graphql-sequelize-crud/lib/index.js:887:10)

Add pre- and post-resolve hooks

Hi!

I'm thinking of using this library, but I was asking myself how I could manage authentication with it (for example with express-jwt or express-session). More specifically, I would pass the token info into the context argument of the resolve function, but with this library I cannot access this resolve function anymore (unless in a custom query, but that's not what I want).

So my idea is to add pre and post hooks on every CRUD action that users can configure themselves. Similar to what is done here: https://github.com/RisingStack/graffiti-mongoose.

Any thoughts about this?

Error creating entries that belongs to other models.

Hi! I may be doing something wrong, but I can't make this to work.

I setup as the example, and when trying to create a new entry, an error from Postgres it's returned.

database model

export const Person = database.define('person', {
  firstName: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  lastName: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  email: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: {
      isEmail: true,
    },
  },
});

export const Post = database.define('post', {
  title: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  content: {
    type: Sequelize.TEXT,
    allowNull: false,
  },
});


Person.hasMany(Post);
Post.belongsTo(Person);

query

mutation addPost(
  $content: String!,
  $title: String!
) 
{
  createPost(
    input: {
      title: $title,
      content: $content,
      personId: 50
    }
  ) {
    newPost {
      title
      content
      createdAt
    }
  }
}

variables

{
  "title": "hola",
  "content": "VVLV"
}

the error (as-is)

{
  "data": {
    "createPost": null
  },
  "errors": [
    {
      "message": "la sintaxis de entrada no es válida para integer: «�»",
      "locations": [
        {
          "line": 20,
          "column": 3
        }
      ],
      "path": [
        "createPost"
      ]
    }
  ]
}

I'm new to GraphQL, but as I understand this is the way to do it. Sorry if this is not.

Thanks you!

Update: I try with SQLite, just to see if I was missing something, and still throwing errors.

{
  "data": {
    "createPost": null
  },
  "errors": [
    {
      "message": "SQLITE_CONSTRAINT: FOREIGN KEY constraint failed",
      "locations": [
        {
          "line": 31,
          "column": 3
        }
      ],
      "path": [
        "createPost"
      ]
    }
  ]
}

It's clearer what's happening, but still, I don't know why it is happen.

UPDATE 2:
Looking in the Sequelize log:

Executing (default): INSERT INTO `posts` (`id`,`title`,`content`,`createdAt`,`updatedAt`,`personId`) VALUES (NULL,'hola','VVLV','2017-01-23 18:41:41.986 +00:00','2017-01-23 18:41:41.986 +00:00','');

The personId it's transformed in some unreadable code somewhere, both to humans and to the SQL interpreter, so it acts like no personId it's provided.

According to the docs, the ID should not be human readable, but still be settable with both, string and integers values.

When expected as an input type, any string (such as "4") or integer (such as 4) input value will be accepted as an ID.

Doc needed: An example of custom query

Hello,

In your readme you say that "Custom queries and mutations within Sequelize Models defitions". Can you give a simple example of how we could implement that?

Thanks.

graphql-sequelize: Include support has been removed

Brilliant work on graphql-sequelize-crud! Looking to make use of this package with latest graphql (v0.7.2) and graphql-sequelize (v4.0.0) updates, but when attempting to run graphql-sequelize-crud Demo after updates get AssertionError: "Include support has been removed in favor of dataloader batching".

Error arises from: graphql-sequelize\lib\resolver.js:41:24 (https://github.com/mickhansen/graphql-sequelize/search?utf8=%E2%9C%93&q=%22Include+support+has+been+removed+in+favor+of+dataloader+batching%22)

After loading dataloader-sequelize package get same error. Have not looked far into a solution, but as you are likely already aware of the issue, was wondering if graphql-sequelize-crud will be updated for graphql-sequelize (v4.0.0)?

Input Types cannot define resolvers

When I am using this library in latest graphql, I can see the below error

CreateusersValuesInput.userId field type has a resolve property, but Input Types cannot define resolvers.
at invariant (/home/michael/revisioner-graphql/node_modules/graphql/jsutils/invariant.js:19:11)

but this problem can be eliminated (with possible problems) by falling back to graphql@^0.8.0
I believe this is due to a breaking API change, how do you guys think of it

Queries with GraphQLList within a GraphQLList don't seem to work

Any help here? Not sure what is going on.
Problem query:

{
  contents(where: {id: "6f94e479-3d72-4e42-ac9f-e4549dca9b1a"}) {
    title
    id
    resources(first: 1) {
      total
      edges {
        node {
          title
          url
        }
      }
    }
  }
}

Problem response:

{
  "data": {
    "contents": [
      {
        "title": "Number Systems Conversion",
        "id": "Y29udGVudDo2Zjk0ZTQ3OS0zZDcyLTRlNDItYWM5Zi1lNDU0OWRjYTliMWE=",
        "resources": {
          "total": 1,
          "edges": [
            {
              "node": {
                "title": null,
                "url": null
              }
            }
          ]
        }
      }
    ]
  }
}

Similar query without nesting that works:

query {
  content(where: {typeId: 1}) {
    title 
  	resources(first: 10) {
      edges {
        node {
          title
        }
      }
    }
  }
}

Response:

{
  "data": {
    "content": {
      "title": "Number Systems Conversion",
      "resources": {
        "edges": [
          {
            "node": {
              "title": "Access the slides"
            }
          }
        ]
      }
    }
  }
}

Can't merge schemas using `mergeSchemas`

when merge multiple schemas using mergeSchemas, it throw error

Error: Can't find type Root.

const { mergeSchemas } = require('graphql-tools')
const { getSchema } = require('graphql-sequelize-crud')

const dbschema1 = getSchema(sequelize1)
const dbschema2 = getSchema(sequelize2)

module.exports = mergeSchemas({
  schemas: [dbschema1, dbschema2]
})

Some questions about features

This is a great project, i'm using it in conjuction to sequelize-auto to totally automate creation of graphql service from pre-existibg mysql db... but i would ask you 3 things that are makes me crazy:

  1. All integer primary keys are trasformed in graphql ID scalar type. So i cannot do for example { mytable(id: 4) } since that values is not recognized. Is there a solution?

  2. In sequelize i've tons of fields that are "not null" but have a default value. But the graphql schema is created with "!" (not null) so i cannot omit them when mutate/create. Is there any way to configure it in a way to avoid it when default value is present in sequelize model?

  3. How can i set a middlewares in resolvers to implement security checks? I need to filter queries/mutations based on user roles.

Add custom schemas and mutations

How to add schemas and resolvers that are not in sequelize models?
I have this folder structure:

  • orm
    • models <- sequelize models here
  • graphql
    • MyCustomGraph
      • resolver.js
      • schema.gql
  • app.js <-- Running with apollo server

Custom mutations and queries

I had to check the source code to figure out how create custom mutations, it would be very helpful include better explanation on the docs.

It would be good mentioning that custom queries and mutations should be included in sequelize models definitions, then provide an example like this.

const user = sequelizeClient.define('user', {
  email: {
    type: Sequelize.STRING,
    allowNull: true,
    unique: false,
  },
  password: {
    type: Sequelize.STRING,
    allowNull: true,
  }
}, {
  classMethods: {
    //queries: function(){},
    mutations: function(Models, ModelTypes, resolver) {
      console.log("Creating custom mutations for model user");
      return {
        myMutationA: {
          type: MyCustomType,
          args: {
            dataA: {
              data: 'dataA',
              type: new GraphQLNonNull(GraphQLString)
            },
            dataB: {
              data: 'dataB',
              type: new GraphQLNonNull(GraphQLString)
            }
          },
          resolve: (obj, {
            name
          }) => {

            console.log("Calling custom mutator with data")
            console.log(name)
            // Here call sequelize using Models in the scope
            let myFirstPromise = new Promise((resolve, reject) => {
              setTimeout(function() {
                resolve("Success!");
              }, 250);
            });

            return myFirstPromise;
          }
        }
      };
    }
  }
});

Is this repo still active/alive?

So, is anyone still maintaining this repo? It is a really cool project so I hope it can be maintained.

In the meantime, we at Teselagen have forked this repo, customized it to our needs, and have published it to npm as graphql-sequelize-crud-teselagen. We've added some new features like counts, batch updates (multiple where queries) and nested creates.

Security issue, the alternative

This library has a security issue:

even if you apply a middleware on a table, this middleware is not applied on same table when called in a nested query. So, for example, if you create an auth middleware on a table, you can access to private data via nested queries instead.

There's an alternative library on which i'm working on currently: https://github.com/alirizwan/sequelize-graphql-schema/ without this issue

Schema could not be fetched when running using local build

Hi @Glavin001 I was trying to use a local copy of your repo but I am getting this error whenever I import directly from the dist/src folder.

Schema could not be fetched.
Please check if the endpoint 'http://localhost:4000/graphql' is a valid GraphQL Endpoint.

Here are the steps

  1. I cloned the repo to a folder
  2. run "npm run all"
  3. on my personal project I use
    import { getSchema } from '../graphql-sequelize-crud/dist/src'
  4. open localhost:4000/playground

my index.js

import express from 'express'
import graphqlHTTP from 'express-graphql'
import { getSchema } from '../graphql-sequelize-crud/dist/src'
// import { getSchema } from 'graphql-sequelize-crud'
import { db as sequelize} from './sql/connector'

const expressPlayground = require('graphql-playground-middleware-express').default

const app = express();

sequelize.sync({
    // force: true
}).then(() => {

    const schema = getSchema(sequelize)

    app.use('/graphql', graphqlHTTP({
        schema,
        graphiql: true
    }));

    app.get('/playground', expressPlayground({ endpoint: '/graphql' }));

    const port = 4000;

    app.listen(port, () => {
        console.log(`Listening on port ${port}`)
    })
    
})

when using the npm package everything works as expected. The error is shown only when using a local build.
Is there anything that I missed? Why am I getting this error?

BTW this is a great library.. I will try to contribute soon if my issue is fixed.

ID (primary key) cannot be used in where clause of GraphQL query

Please check out stackoverflow
Below are just my thoughts:
Bascially when you use a int column in database as PK or FK, this library will treat it as a GraphQLID, which is considered a string. Hence when it process the client side data from the id field, which is provided as int, it treat it as string and eventually says NaN when attempting to convert it to a number.
Please fix!

Error: Mutations fields must be an object with field names as keys or a function which returns such an object.

Not sure if I should ask here or upstream. I'm trying to run this tool on an existing api running sequelize.

$ node index.js
{"name":"foo","version":"0.0.1","event":"state","state":"booting"}
/Users/harrymoreno/programming/foo/node_modules/graphql/jsutils/invariant.js:19
    throw new Error(message);
    ^

Error: Mutations fields must be an object with field names as keys or a function which returns such an object.
    at invariant (/Users/harrymoreno/programming/foo/node_modules/graphql/jsutils/invariant.js:19:11)
    at defineFieldMap (/Users/harrymoreno/programming/foo/node_modules/graphql/type/definition.js:324:27)
    at GraphQLObjectType.getFields (/Users/harrymoreno/programming/foo/node_modules/graphql/type/definition.js:285:44)
    at /Users/harrymoreno/programming/foo/node_modules/graphql/type/schema.js:207:27
    at typeMapReducer (/Users/harrymoreno/programming/foo/node_modules/graphql/type/schema.js:219:7)
    at Array.reduce (native)
    at new GraphQLSchema (/Users/harrymoreno/programming/foo/node_modules/graphql/type/schema.js:95:34)
    at getSchema (/Users/harrymoreno/programming/foo/node_modules/graphql-sequelize-crud/lib/index.js:887:10)

Is my data model not compatible with graphql?

Trying to choose ASC or DESC in order argument

I'm looking into sorting graphQL result depending on updatedAt setting:

Here is my query :

{payments(order: "updatedAt", where: + where + ){ id, state, token, amount, bankData, comment, createdAt, updatedAt, PaymentOrder, payment_order{ id, priceTaxIncluded, user_orders{firstName, lastName} }

I have a problem with the order argument.

I'm not able to sort ASC or DESC, as order arguments ask for a String I could not find any method to sort the result.

I tried with :
"updatedAt DESC"
"updatedAt_DESC"

but both fails

Any idea ?

Thank you

Add `through` Model fields to Edge

For example:

    TodoAssignee = sequelize.define('TodoAssignee', {
      primary: {
        type: Sequelize.BOOLEAN
      }
    }, {
      timestamps: false
    });

    // belongsToMany
    User.belongsToMany(Todo, {
      as: 'assignedTodos',
      through: TodoAssignee
    });
    Todo.belongsToMany(User, {
      as: 'assignees',
      through: TodoAssignee
    });

Will now have primary field on the Edge.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.