sarkistlt / mongoose-schema-to-graphql Goto Github PK
View Code? Open in Web Editor NEWUse Mongoose schema to generate graphQL type.
Use Mongoose schema to generate graphQL type.
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
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:
mongoose-schema-to-graphql/src/index.js
Line 104 in 8e64d0d
mongoose-schema-to-graphql/src/index.js
Line 113 in 8e64d0d
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.
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
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
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.
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
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
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?
const createType = require('mongoose-schema-to-graphql')
// built index.js line 291
exports.default = createType;
not work
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?
Hi @sarkistlt
Great module, thanks!
Does your module support mongoose document population?
How does this compare to the mongoose-graffiti module in your opinion?
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'.
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.
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!
I would like to suggest to add a support for regular expressions in exclude
option.
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.
Could you share the ES6 version of the index.js file, before it be transpiled?
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.
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)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.