Giter Site home page Giter Site logo

mongoose-schema-to-graphql's People

Contributors

comonadd avatar ignacioureta avatar kettanaito avatar khaledosman avatar sarkistlt avatar sonivaibhav26 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  avatar

mongoose-schema-to-graphql's Issues

"Number" not supporting Date.now()

Could you change the mapping of Number to GraphQLFloat too allow for the sending of javascript timestamps?

const foo = mongoose.Schema({
  time: { type: Number, default: Date.now }
})

// ...

resolve:()=>({ time: Date.now() })

Thanks

Recursive Mongoose schema

Suppose you are writing a forum API, which has a recursive schema called Message defined like this:

const MessageTypeMongoose = new mongoose.Schema({
  text: String,
});

// This is how you define recursive Mongoose schema
MessageTypeMongoose.add({
  messages: [MessageTypeMongoose],
});

Now, because you don't want to write the same thing two times, you are using mongoose-schema-to-graphql library, and the definition of your GraphQL schema looks like this:

const MessageTypeGraphQL = mongooseSchemaToGraphQL({
  name: 'Message',
  class: 'GraphQLObjectType',
  schema: MessageTypeMongoose,
});

But, when you would run this code, you will get a funny stack overflow error message, which looks like this:

RangeError: Maximum call size exceeded
  at Array.forEach (native)
  at createType( /*...*/ /node_modules/mongoose-schema-to-graph/lib/index.js:1:1747)
  //...

I've tried to figure out where is the infinite recursion happens:

  • First, if you pass a schema in which the recursively defined field is an array, the infinite recursion happens here

GQLS.fields[key] = { type: createType(subArgs) };

  • Second, if you pass a schema in which the recursively defined field is not an array, the infinite recursion happens here

const typeElement = createType(subArgs);

If we won't fix this issue, other users would be in a trouble, - they would waste big amount of time. It is very hard to figure out which mongooseSchemaToGraphQL call caused this problem.

NOTE: It is totally possible to define a recursive GraphQL type. Look at this SO answer.

How to set a resolve?

I am trying to setup a helloworld, but dont know how to add a resolve?

I have tried adding one to "createType"

const user = mongoose.Schema({ name: String })
const User = createType({
    name: 'User',  schema: user,
    class: 'GraphQLObjectType',
    resolve:()=>({name:"Ann2"})
}); // END createType: User

and as a "rootValue"

app.use('/graphql', graphqlHTTP({
  schema:new GraphQLSchema({ query:User }),
  rootValue: {
    User:()=>({  name:"Ann1" })
  }, // END rootValue
  graphiql: true
})); // END graphqlHTTP

but they ever get fired.

Thanks for any help

Errors with the created types

TL;DR:
The import didn't worked on typescript, so after many approaches, i changed the export from the package to:

export default function createType(config: ConfigurationObject): any;

But now i got this error:

suscriptorType.obj field type must be Output Type but got: undefined.

My code:

const suscriptorSchema = new mongoose.Schema({ mail: String })
const suscriptor = mongoose.model('Suscriptor', suscriptorSchema);
const suscriptorGQL = createType({
    name: 'suscriptorType',
    description: '',
    class: 'GraphQLObjectType' as ClassFieldType,
    schema: suscriptorSchema,
    extend: {}
})

I was using version 2.5.7 without problems, but when i tried to update to version 2.6.8 i couldn't make the import work, and now that i solved that this problem occur. I would love some help to integrate the new version

field type must be Output Type but got: undefined

Hi,

Whatever I try with my Mongoose schemas, I always get this error.
Error: Query.LMEs field type must be Output Type but got: undefined.

var LMEQueries = {
  LMELastMonthAverages: {
    type: LMEAgType,
    resolve: LME.lastmonthavgall
  },
  LMEs: {
    type: LMEType,
    resolve: LME.allLMEs
  }
};


let RootQuery = new GraphQLObjectType({
  name: 'Query',      //Return this type of object
  fields: () => ({    // list all queries here with links to resolvers
    LMEAveragesLastMonth: LMEQueries.LMELastMonthAverages,
    LMEs: LMEQueries.LMEs,
    Users: UserQueries.allUsers
  })
});

...

let schema = new GraphQLSchema({
  query: RootQuery/*,
  mutation: RootMutation*/
});

And the Schema is (shortened)

var LMESchema = new Schema({
    date: Schema.Types.Date,
    copper: [Copper],
    alAlloy: [AlAlloy],
    naAlloy: [NAAlloy],
    aluminium: [Aluminium],
    zinc: [Zinc],
    lead: [Lead],
    tin: [Tin],
    nickel: [Nickel],
    globalSteel: [GlobalSteel],
    cobalt: [Cobalt],
    molybdenum: [Molybdenum],
    forex: [Forex]
});

// each of the arrays are defined as a separate types e.g.

var Copper = new Schema ({
    cashBuyer: Number,
    cashSeller: Number,
    threeMBuyer: Number,
    threeMSeller: Number,
    december1Buyer: Number,
    december1Seller: Number,
    december2Buyer: Number,
    december2Seller: Number,
    december3Buyer: Number,
    december3Seller: Number,
    ABR: Number
});

LMESchema.set('toJSON', { getters: true });

var LME = mongoose.model('LME', LMESchema);

module.exports = LME;

module.exports.allLMEs = function(){
  return new Promise(
    (resolve, reject) => {
      LME.find().then((err, results)=> err ? reject(err): resolve(results) );
    }
  );
}

and finally

var createType = require('mongoose-schema-to-graphql').default;
var LMESchema = require('./LMESchema');

let queryConfig = {
  name: 'LME',
  description: 'LME type',
  class: 'GraphQLObjectType',
  schema: LMESchema
  //exclude: ['mongooseId']
};


let LMEType = createType(queryConfig);

module.exports = LMEType;

I looked at your source, and I don't see a case where it returns undefined.
Can you guess what this is about?

Thanks.

Grapiql example

Great work.
can you provide an example how can we expose these graphql types through graphiql so that it can be consumed by the UI

Generation of schema with array of refs to another collection doesn't work

If I have the following field type in mongoose schema

MySchema = new mongoose.Schema({
    items: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Item',
    }],
});

And I want to generate graphql schema using this:

ExerciseType = createType({
    name: 'MyType',
    description: 'My schema',
    class: 'GraphQLObjectType',
    schema: MySchema,
    exclude: ['items'],
    extend: {
      items: {
        type: new GraphQLList(ItemType),
        resolve: (root, params, context) => {
          ...
        },
      },
    },
});

I get the following error:

Error:
type with name "Item" doesn't exist,
but was specified as population reference.

As I understand when I exclude items field and extend this schema with my custom field it should skip generation of items and use my custom specification for this field

Cannot Generate GraphQL schemas with nested Mongoose Schemas

Hi I was trying to create a mongoose schema and convert it into graphql. The structure is the following

export const BlogSchema = new Schema({
  tags: [{
    type: String,
  }],
  category: {
    type: String
  },
  cover: {
    photo: String,
    video: String,
  },

Then the it doesn't generate a graphql schema. Here is the error:

{
  "errors": [
    {
      "message": "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"cover.photo\" does not.\n\nNames must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"cover.video\" does not.\n\nThe type of BlogType.cover must be Output Type but got: undefined.\n\nThe type of blogMutate.default must be Output Type but got: undefined."
    }
  ]
}

Initially, I have an assumption that the error was from
node_modules\graphql\utilities\assertValidName.js and it asserts that those fields are not valid. Do you of possible fix for it or workaround?

It's not a commonJS module

const createType = require('mongoose-schema-to-graphql')
// built index.js line 291
exports.default = createType;

not work

Circular references not supported

It is said in the docs that in case of a circular reference of types (i.e. Person has a house and the house has Persons),

Quoted from official documentation

http://graphql.org/docs/api-reference-type-system/

When two types need to refer to each other, or a type needs to refer to itself in a field, you can use a function expression (aka a closure or a thunk) to supply the fields lazily.

I'm currently needing this and i've seen more people in the same situation. Should i do a PR with this or is it currently under development?

Mongoose population?

Hi @sarkistlt

Great module, thanks!

Does your module support mongoose document population?
How does this compare to the mongoose-graffiti module in your opinion?

Trying to use with TS, but get this error

error TS2345: Argument of type '{ name: string; description: string; class: string; schema: any; }' is not assignable to parameter of type 'ConfigurationObject'.
Types of property 'class' are incompatible.
Type 'string' is not assignable to type 'ClassFieldType'.

Changing [string] to string[] in index.d.ts

Hi,

In the Typescript declaration file, shouldn't the exclude field in the type ConfigurationObject be a string[] (string array) instead of a [string] (tuple with one element of type string)? If the latter is used (which it is), Typescript throws an error when having more than one element in the array (i.e. when excluding multiple fields).

Basically, shouldn't this
exclude?: RegExp | [string],
be changed to this
exclude?: RegExp | string[],

Thanks.

1:1 Help

Would you be open to a 1:1 Google Hangout for pay? Need some help. Running into several issues. Thanks! Please ping me here and we can set something up. Thanks!

Add RegExp support for "exclude" option

What

I would like to suggest to add a support for regular expressions in exclude option.

Why

There is a particular use case I can give you: with the recent update of graphql, it will no longer accept fields which start with __, as it is used internally for the library. For that matter, when converting schemas to types you would need to exclude each schema field starting with __ manually.

I find this tedious and non future-proof. No one can predict the changes in both libraries in the future, so the exclusion on our side should be as simple and minimal as possible.

Managing this exclusion with the RegExp would be a good option to go:

const schema = { ... };

const type = createType({
  schema,
  exclude: /^__[^_]\S+/
});

So all fields starting with two underscores are excluded from the generated type.

Please let me know what do you think of this. Thanks.

ES6 version

Could you share the ES6 version of the index.js file, before it be transpiled?

Mapping fields name

Hi,

Is there a way to map the fields (eg. _id => id) and vice versa ?

Something like this :

createType({
    name: 'User',
    description: 'an application user',
    class: 'GraphQLObjectType',
    schema: User,
    map: {
        displayName: 'name',
        '_id': 'id'
    },// or Map, or func
    exclude: ['auths']
})

Thanks.

Can't create type with .default

Version "mongoose-schema-to-graphql": "^2.7.2"
My type:

const createType = require('mongoose-schema-to-graphql').default;
const Calendar = require('../../models/calendar');

module.exports = createType({
  name: 'Calendar',
  description: 'Calendar collection type',
  class: 'GraphQLObjectType',
  schema: Calendar.schema,
  exclude: ['_id']
});

Returns this error:

module.exports = createType({
                 ^
TypeError: createType is not a function

If I use withiut .default I'm having only created name (in this case name = Calendar). So this will create new error:
GraphQLError: Syntax Error: Unexpected Name "Calendar"


Where I can find normal example with this implementation? (example app)

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.