Giter VIP home page Giter VIP logo

graphql-compose-mongoose's Introduction

graphql-compose

codecov coverage Travis npm Commitizen friendly TypeScript compatible Backers on Open Collective Sponsors on Open Collective

graphql-compose – provides a type registry with a bunch of methods for programmatic schema construction. It allows not only to extend types but also remove fields, interfaces, args. If you want to write your graphql schema generator – graphql-compose is a good instrument for you.

  • provides methods for editing GraphQL output/input types (add/remove fields/args/interfaces)
  • introduces Resolver's – the named graphql fieldConfigs, which can be used for finding, updating, removing records
  • provides an easy way for creating relations between types via Resolver's
  • provides converter from OutputType to InputType
  • provides projection parser from AST
  • provides GraphQL schema language for defining simple types
  • adds additional types Date, Json

And a little bit more

graphql-compose-[plugin] – are declarative generators/plugins built on top of graphql-compose, which take some ORMs, schema definitions and create GraphQL Models from them or modify existing GraphQL Types.

Type generators built on top graphql-compose

Utility plugins:

Documentation

graphql-compose.github.io

Live Demos

Examples

Please follow Quick Start Guide for the complete example.

Here is just a demo of ambiguity ways of types definitions:

import { schemaComposer} from 'graphql-compose';

// You may use SDL format for type definition
const CityTC = schemaComposer.createObjectTC(`
  type City {
    code: String!
    name: String!
    population: Number
    countryCode: String
    tz: String
  }
`);

// Define type via Config object
const CountryTC = schemaComposer.createObjectTC({
  name: 'Country',
  fields: {
    title: 'String',
    geo: `type LonLat { lon: Float, lat: Float }`,
    hoisting: {
      type: () => AnotherTC,
      description: `
        You may wrap type in thunk for solving
        hoisting problems when two types cross reference
        each other.
      `,
    }
  }
});

// Or via declarative methods define some additional fields
CityTC.addFields({
  country: CountryTC, // some another Type
  ucName: { // standard GraphQL like field definition
    type: GraphQLString,
    resolve: (source) => source.name.toUpperCase(),
  },
  currentLocalTime: { // extended GraphQL Compose field definition
    type: 'Date',
    resolve: (source) => moment().tz(source.tz).format(),
    projection: { tz: true }, // load `tz` from database, when requested only `localTime` field
  },
  counter: 'Int', // shortening for only type definition for field
  complex: `type ComplexType {
    subField1: String
    subField2: Float
    subField3: Boolean
    subField4: ID
    subField5: JSON
    subField6: Date
  }`,
  list0: {
    type: '[String]',
    description: 'Array of strings',
  },
  list1: '[String]',
  list2: ['String'],
  list3: [new GraphQLOutputType(...)],
  list4: [`type Complex2Type { f1: Float, f2: Int }`],
});

// Add resolver method
CityTC.addResolver({
  kind: 'query',
  name: 'findMany',
  args: {
    filter: `input CityFilterInput {
      code: String!
    }`,
    limit: {
      type: 'Int',
      defaultValue: 20,
    },
    skip: 'Int',
    // ... other args if needed
  },
  type: [CityTC], // array of cities
  resolve: async ({ args, context }) => {
    return context.someCityDB
      .findMany(args.filter)
      .limit(args.limit)
      .skip(args.skip);
  },
});

// Remove `tz` field from schema
CityTC.removeField('tz');

// Add description to field
CityTC.extendField('name', {
  description: 'City name',
});

schemaComposer.Query.addFields({
  cities: CityTC.getResolver('findMany'),
  currentTime: {
    type: 'Date',
    resolve: () => Date.now(),
  },
});

schemaComposer.Mutation.addFields({
  createCity: CityTC.getResolver('createOne'),
  updateCity: CityTC.getResolver('updateById'),
  ...adminAccess({
    removeCity: CityTC.getResolver('removeById'),
  }),
});

function adminAccess(resolvers) {
  Object.keys(resolvers).forEach(k => {
    resolvers[k] = resolvers[k].wrapResolve(next => rp => {
      // rp = resolveParams = { source, args, context, info }
      if (!rp.context.isAdmin) {
        throw new Error('You should be admin, to have access to this action.');
      }
      return next(rp);
    });
  });
  return resolvers;
}

// construct schema which can be passed to express-graphql, apollo-server or graphql-yoga
export const schema = schemaComposer.buildSchema();

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

MIT

graphql-compose-mongoose's People

Contributors

antoniopresto avatar benny1hk avatar berrymat avatar canac avatar corydeppen avatar danez avatar dependabot[bot] avatar exneval avatar francois-spectre avatar greenkeeper[bot] avatar greenkeeperio-bot avatar israelglar avatar janfabian avatar lihail-melio avatar mattslight avatar meabed avatar mernxl avatar michaelbeaumont avatar natac13 avatar neverbehave avatar nodkz avatar oklas avatar oluwatemilorun avatar petemac88 avatar robertlowe avatar sgpinkus avatar toverux avatar unkleho avatar yoadsn avatar yossisp 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphql-compose-mongoose's Issues

Support for Mongoose Populate

Mongoose provides a way to define relationships between schema,
I was wondering why do we have to define relationships separately as we can iterate over the mongoose model to find out 'ref' fields from the schema definition and build up the populate query as you do for projection fields

Insert JSON in mutation from server code

I have a simple model with a single JSON field.

const UserSchema = new mongoose.Schema({
  profile: mongoose.Schema.Types.Mixed,
});
const UserModel = mongoose.model('users', UserSchema);
const UserTC = composeWithMongoose(UserModel);
...mutation methods left out 

How do I insert JSON into that field using a server-side query?

let profile = {test: "profile"}
let mutationQuery_NewUser = `
  mutation {
    userCreate(record:{
      profile: ${profile},
    }) {
      recordId
    }
  }
`
graphql.graphql(mySchema, mutationQuery_NewUser)

This does not work ([Object object] tries to get inserted), and neither does replacing with a JSON.stringified value, or anything else I could think of.

Is it possible to cast the JSON scalar to something else for input?

how to add mongodb $near to filter

Hello

how to add filter to use $near
my addressBook schema is

import { Schema } from 'mongoose';

export const AddressBook = new Schema({
  title: {
    type: String,
    description: "Title of this address",
  },
  country: {
      type: String,
      description: "Counry of the account",
      indexed: true
  },
  region: {
      type: String,
      description: "Region of the account",
      indexed: true
  },
  city: {
      type: String,
      description: "City of the account",
      indexed: true
  },
  postalcode: {
    type: String,
    description: "City of the account",
    indexed: true
  },
  street: {
      type: String,
      description: "Phisical Address of the account"
  },
  latitude: {
      type: Number,
      description: "latitude",
      indexed: true
  },
  longitude: {
      type: Number,
      description: "longitude",
      indexed: true
  }
}, {
  collection: 'addressbook'
});

and my User Schame

import mongoose, { Schema } from 'mongoose';
import composeWithMongoose from 'graphql-compose-mongoose';
import composeWithRelay from 'graphql-compose-relay';

import { AddressBook } from './addressBook';
export const UserSchema = new Schema({
    name: String,
    email: {
        type: String,
        set: v => v.toLowerCase().trim(),
        unique: true,
        indexed: true
    },
    address:{
      type:[AddressBook],
      indexed:true
    },
}, {
  collection: 'users',
});

export const User = mongoose.model('User', UserSchema);
export const UserTC = composeWithRelay(composeWithMongoose(User));

many thanks in advance

About Connection Resolvers

May I suggest you add more information about the functionality of graphql-compose-connections. At least for me, connection reminds of relay. Since I'm not using relay, I feel I have no use for 'connection'. However, it appears "connections" resolvers are useful beyond relay particular, within the context of this package. Indeed, can you explain the use case of 'connection' resolvers?

Null fields in mongo return sub fields

Hey,
I am not sure where this behavior is coming from.. have been debugging both graphql-compose* and graphql-js for the past 5 hours. Any help in the right direction would be great!

Assume this mongodb document:

{
 _id: objectId("5816f273f3bb751f5021d849"),
 someField: null
}

And this mongoose schema:

let inner = {
 otherField: String
}

let MyType = Schema({
  someField: inner
})

The following gql query (assume the getOne field returns the above document):

query {
  getOne(_id: "5816f273f3bb751f5021d849") {
    someField {
      otherField
    }
  }
}

I expect to get:

{
   "data" : {
    "getOne" : {
      someField: null
    }
  }
}

This is for example what graffiti-mongoose returns..
But from graphql-compose* I get:

{
   "data" : {
    "getOne" : {
      someField: {
        otherField: null
      }
    }
  }
}

Am I expecting the wrong behavior? I found this issue graphql/graphql-js#424 that support what I expect (I think). Where is the difference?
So far I reached the conclusion that graphql-js does not recognize the value for "someField" to be null here:
https://github.com/graphql/graphql-js/blob/73513d35747cdea255156edbe30d85d9bd0c1b81/src/execution/execute.js#L774
I'm using graphql 0.7.2 although this specific code seems to remain the same in 0.8*.

Thanks!

findByIds resolver issue with multiple Schemas using useDb()

Previously when there was only one schema this worked, where source.attributes is an array of MongoIDs.

AttributeGroupTC.addRelation(
'attributesData', {
    resolver: () => AttributeTC.get('$findByIds'),
    prepareArgs: {
      _ids: (source) => source.attributes,
    },
    projection: { attributes: true },
  },
);

After multiple schemas, findByIds resolves to null, only findMany works like below:

schema.js
const getSchema = (db: any) => {
  const GQC = new ComposeStorage();

  const ViewerTC = GQC.get('Viewer');
  GQC.rootQuery().addFields({
    viewer: {
      type: ViewerTC.getType(),
      description: 'Data under client context',
      resolve: () => ({}),
    },
  });
  const fields = {
    attributeGroup: AttributeGroup.getTC(db).get('$findOne'),
    attributeGroupList: AttributeGroup.getTC(db).get('$findMany'),

    attribute: Attribute.getTC(db).get('$findOne'),
    attributeList: Attribute.getTC(db).get('$findMany'),
  };

  ViewerTC.addFields(fields);

  return GQC.buildSchema();
};

export default { getSchema };
attribute.js
const AttributeSchema = () => new Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  ...
},
{
  collection: 'attributes',
});
const cache = {};

const getTC = (db: any) => {
  if (cache[db.name] && cache[db.name].TC) {
    return cache[db.name].TC;
  }
  const dbModel = db.model('attribute', AttributeSchema());
  mongooseTypeStorage.clear();
  const AttributeTC = composeWithDataLoader(composeWithMongoose(dbModel), { cacheExpiration: 10000 });
  cache[db.name] = {
    ...cache[db.name],
    TC: AttributeTC,
  };
  return AttributeTC;
};

export default { getTC };
attributeGroup.js
import Attribute from './attribute';

const AttributeGroupSchema = () => new Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  attributes: [Schema.Types.ObjectId],
},
{
  collection: 'attribute_groups',
});
const cache = {};

const getTC = (db: any) => {
  if (cache[db.name] && cache[db.name].TC) {
    return cache[db.name].TC;
  }

  const dbModel = db.model('AttributeGroup', AttributeGroupSchema());
  mongooseTypeStorage.clear();
  const AttributeGroupTC = composeWithDataLoader(composeWithMongoose(dbModel), { cacheExpiration: 10000 });
  AttributeGroupTC.addRelation(
    'attributesData', {
      resolver: () => Attribute.getTC(db).get('$findMany'),
      prepareArgs: {
        filter: source => ({
          _operators: {
            _id: { in: source.attributes },
          },
        }),
      },
      projection: { attributes: true },
    },
  );
  cache[db.name] = {
    ...cache[db.name],
    TC: AttributeGroupTC,
  };
  return AttributeGroupTC;
};

export default { getTC };

Here is my package.json

    "graphql-compose": "^2.2.0",
    "graphql-compose-connection": "^2.2.2",
    "graphql-compose-dataloader": "^1.1.2",
    "graphql-compose-mongoose": "^1.6.0",

GraphQL 0.11 : Can only create NonNull of a Nullable GraphQLType but got: MongoID

One of the drawbacks of pre-v1 software is instability and GraphQL does not escapes that rule 😄

Starting from GraphQL v.0.11.0 and later, the app crashes when building the schema. Relavant stack trace:

/home/morgan/.../node_modules/graphql/jsutils/invariant.js:19
    throw new Error(message);
          ^
Error: Can only create NonNull of a Nullable GraphQLType but got: MongoID.
    at invariant (/home/morgan/.../node_modules/graphql/jsutils/invariant.js:19:11)
    at new GraphQLNonNull (/home/morgan/.../node_modules/graphql/type/definition.js:780:84)

I assume that a breaking change in GQL breaks graphql-compose-mongoose.

(Workaround: downgrade to [email protected])

Old good pagination

Hello,

I want to use pagination ({ totalCount: Number, currentPage: Number, itemsPerPage: Number, totalPages: Number }). Is it possible to add that?

Thanks.

schema for nest model

I have a user <-> company relation
so I build like that

const UserSchema = new mongoose.Schema({
  company: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company'
  }
})

after adding relation, it works with RootQuery.

However, it failed when I try to RootMutation user with companyId.
The graphql console shows that company is "GQLReference" not MongoID or String type
till I wrote

const UserSchema = new mongoose.Schema({
  company: {
    type: String,
  }
})

to make RootQuery and RootMutation available.

Did I miss anything?

Nested SubSchema array has "Generic" type

This is similar to issue #2, but even when I use mongoose.Schema the resulting field still has "Generic" type

I can replicate this using the example from README.md

const mongoose = require('mongoose')
const { composeWithMongoose } = require('graphql-compose-mongoose')
const { GQC } = require('graphql-compose')

const LanguagesSchema = new mongoose.Schema({
  language: String
});

const UserSchema = new mongoose.Schema({
  name: String,
  languages: {
    type: [LanguagesSchema],
    default: [],
  }
});
const UserModel = mongoose.model('UserModel', UserSchema);
const UserTC = composeWithMongoose(UserModel);

UserTC.get('languages') // Generic

I'm using the following versions

    "graphql-compose": "^1.8.0",
    "graphql-compose-connection": "^2.1.2",
    "graphql-compose-mongoose": "^1.4.2",
    "mongoose": "^4.7.4",

_id is stripped from embedded documents

This issue was driving me mad, so I followed the source code only to find that this is by design.

The _id is removed during the conversion from model to graphql (#L306 and #L351).

I want to write a query like this:

query {
  accounts {
    _id
    name
    websites {
    	_id
      domain
      description
    }
  }
}

My front-end relies on the _id field of the embedded website documents, so I'm a bit confused what the purpose of removing them is.

Here is my Account schema:

const WebsiteSchema = new Schema({
  domain: String,
  description: String
});

const AccountSchema = new Schema({
  name: String,
  createdAt: Date,
  updatedAt: Date,
  deletedAt: Date,
  ...
  websites: [WebsiteSchema]
});

latest release breaks the server.

/Users/ddcole/_dev/servers/jitter-party-server2/node_modules/graphql-compose-mongoose/lib/fieldsConverter.js:206

function convertFieldToGraphQL(field, prefix = '') {

SyntaxError: Unexpected token =

Nested arrays of objects use "Generic" type

When a schema has an array of objects, the GraphQL type is GraphQLList of GraphQLObjectType, but when that array of objects is inside a nested object, the type is a "Generic" GraphQLScalarType.

> var mongoose = require('mongoose')
undefined
> var composeWithMongoose = require('graphql-compose-mongoose').default
undefined
> var model = mongoose.model('doc', new mongoose.Schema({
... arr: [{ sub: Number }]
... }))
undefined
> var tc = composeWithMongoose(model)
undefined
> tc.getField('arr')
{ type: 
   GraphQLList {
     ofType: 
      GraphQLObjectType {
        name: 'docArr',
        description: undefined,
        isTypeOf: undefined,
        _typeConfig: [Object] } },
  description: undefined }
> var model2 = mongoose.model('doc2', new mongoose.Schema({
... nested: { arr: [{ sub: Number }] }
... }))
undefined
> var tc2 = composeWithMongoose(model2)
undefined
> tc2.getByPath('nested').getField('arr')
{ type: 
   GraphQLScalarType {
     name: 'Generic',
     description: undefined,
     _scalarConfig: 
      { name: 'Generic',
        serialize: [Function: coerceDate],
        parseValue: [Function: coerceDate],
        parseLiteral: [Function: parseLiteral] } },
  description: undefined }

Is this supported? Thanks.

Avoid request to get only _id in relationship

Hello,

I have these models:

Proposal {
  offer: Offer
}
Offer {
  acceptedProposal: Proposal
}

I'd like to make a graphql request to get many Offers, and check if they have an acceptedProposal or not.
For that, I can do this:

query {
  offers {
    acceptedProposal {
      _id
    }
  }
}

But this will make a request for each offer with an acceptedProposal, to get the _id. Even though we already have the acceptedProposal's _id in Offer.
Is there an easy way to avoid these requests? For now I simply declared the relation like this:

tc.addRelation('acceptedProposal', {
    resolver: () => proposalType.getResolver('findById'),
    prepareArgs: { _id: (source: IOfferDocument) => source.acceptedProposal },
    projection: { acceptedProposal: true }
});

I know I could create a new field like acceptedProposalId which will return the id directly (or the inverse, rename the relation so that I still can get the id with acceptedProposal), but I'd like to avoid to complexify the API.
Maybe we could allow the relation field to be of composed type MongoId | Proposal in some way, so it can handle nicely this case where we don't want any Proposal field?

Thanks a lot for your awesome graphql-compose packages :)

Removing mongoId field in a query fails

HI,

Basically I have a schema with a mongoID in a field, and I would like to set it to null.
But everytime I run the query with the variables

{
  "input": {
    "_id": "59a59d8f9ae4fd3eb6e99b3a",
    "parentId": null
  }
}

The mongoId validator will give the error:
"message": "FolderModel validation failed: parentId: Cast to ObjectID failed for value \"null\" at path \"parentId\"",

Sub documents.

Suppose I have subsets on a document like so,

friends : [ {userId: string, meta: {}},... ]

Where meta contains discriminator for the type of friend

How whould I create a relation on freinds that resolves to friends where meta.mutual = 1, and returning a list of friend Profile objects where the Profile object represents a subset user fields e.g.,
{ username, avatar, userId, ....}?

FindMany filter arg type MongoID need to be coverted to string type

I found that findMany resolver's filter arg that has MongoID type doesn't work with mongoID input.

This is what it should be?, I think it will be better if it can work without toString().

Example

....
    addRelation({
      name: 'episodesRelation',
      args: {
        filter: source => ({
          seasonId: source._id.toString(),  // this one need to be converted to String
        }),
      },
      resolver: EpisodeTC.getResolver('findMany'),
      projection: { _id: 1 },
    })

.....
    addFields({
      episodesFields: {
        type: EpisodeTC.getTypePlural(),
        args: {
          offset: { type: 'Int', defaultValue: 0 },
          limit: { type: 'Int', defaultValue: 10 },
        },
        // this directly one doesn't
        resolve: (source, { offset, limit }, { Episode }) => 
          Episode.find({ seasonId: source._id })
          .skip(offset)
          .limit(limit),
      },
    })

.... 
  addRelation({
      name: 'episodesRelation',
      argsMapper: {
        filter: source => ({
          seasonId: source._id, // this deprecated one doesn't too 😆
        }),
      },
      resolver: EpisodeTC.getResolver('findByIds'),
      projection: { _id: 1 },
    })

How to use with graphql-compose-relay

I want to use the generated types with graphql-compose-relay but I am not sure how:

let UserTC = composeWithRelay(composeWithMongoose(User));

UserTC.addResolver({
  name: 'testResolver',
  kind: 'mutation',
  ...
  args: {
    arg1: 'String'
  }
});

GQC.rootMutation.addFields({
  'createOne': UserTC.getResolver('createOne'),
  'testResolver': UserTC.getResolver('testResolver')
});

If I do the above, then createOne has RelayCreateOneUserInput type as the input argument, which I think is right for relay, but for testResolver it has arg1: String as the input argument, which I think is wrong.

I tried changing where composeWithRelay is called but it's still not right:

let UserTC = composeWithMongoose(User);

UserTC.addResolver({
  name: 'testResolver',
  kind: 'mutation',
  ...
  args: {
    arg1: 'String'
  }
});

UserTC = composeWithRelay(UserTC);

GQC.rootMutation.addFields({
  'createOne': UserTC.getResolver('createOne'),
  'testResolver': UserTC.getResolver('testResolver')
});

But the above is still not right because now testResolver has RelayTestResolverInput type, which I think is correct but now createOne has RelayCreateOneUserInput defined as:

record: CreateOneUserInput!
clientMutationId: String

So the input argument for createOne got wrapped twice I think?

graphql 0.10.0 breaking changes

This update seem to break the type resolution. I'm not sure if this is a graphql-compose issue.

GQC: can not convert field 'UserModelName.first' to InputType
      It should be GraphQLObjectType, but got 
      String
GQC: can not convert field 'UserModel.email' to InputType
      It should be GraphQLObjectType, but got 
      String

Stack overflow in fieldsConverter

Given the following schema, with a recursive document array, we get a stack overflow within the lib/fieldsConverter.js file.
code:

const Schema = new mongoose.Schema({
  sometype: String
});
Schema.add({ recursiveType: [Schema] });

error:

.../node_modules/graphql-compose-mongoose/lib/fieldsConverter.js:149
  var typeComposer = new _graphqlCompose.TypeComposer(_typeStorage2.default.getOrSet(typeName, new _graphql.GraphQLObjectType({
                                                                                                           ^
RangeError: Maximum call stack size exceeded
    at convertModelToGraphQL (.../node_modules/graphql-compose-mongoose/lib/fieldsConverter.js:149:108)
    at documentArrayToGraphQL (.../node_modules/graphql-compose-mongoose/lib/fieldsConverter.js:346:22)
    at convertFieldToGraphQL (.../node_modules/graphql-compose-mongoose/lib/fieldsConverter.js:218:14)
    at .../node_modules/graphql-compose-mongoose/lib/fieldsConverter.js:162:13
    at Array.forEach (native)
    at convertModelToGraphQL (.../node_modules/graphql-compose-mongoose/lib/fieldsConverter.js:159:39)

What is the type of an array of embedded docs?

I have this schema:

const MySchema = new Schema({
   name: {type: String},
   embedded: {type: [{foo: {type: String}, bar: {type: String}]}
});

I later on want to create resolver so I can updated embedded in a mutation. In the addResolver call to make the mutation, for the args setting, what do I put as the type for embedded?

Discussion - Names of embedded schema GQL Types

Assume I have this schema:

let imageDataStructure = Schema({
  url: String,
  creditsTo: String,
  creditsLink: String,
  dimensions : {
    aspectRatio: Number
  },
  metadata: {
    leadColor: String,
    gravityCenter: {
      x: Number,
      y: Number
    }
  }
}, { _id: false });

let homeSchema = Schema({
  address: String,
  streetImage: imageDataStructure
})

let agentSchema = Schema({
  first: String,
  last: String,
  profileImage: imageDataStructure
})

The generated GQL types (depending on order of schema parsing) would be:

homeSchema.streetImage -> HomeStreetImage
agentSchema.profileImage -> HomeStreetImage

The type is reused since it's the same mongoose schema. The name is picked by the first path that discovers this schema. All of that takes place in fieldsConverter.js around embeddedToGraphQL.

Now if I would create the image structure like so:

let imageDataStructure = {
  url: String,
  creditsTo: String,
  creditsLink: String,
  dimensions : {
    aspectRatio: Number
  },
  metadata: {
    leadColor: String,
    gravityCenter: {
      x: Number,
      y: Number
    }
  }
};

... reset is the same

the following GQL types are expected:

homeSchema.streetImage -> HomeStreetImage
agentSchema.profileImage -> AgentProfileImage

It's not the same mongoose schema - and so a new Type would be generated for each path.

Since the structure of the embedded image data is the same. I would assume it's useful to create GQL fragments for this type and use it where ever a type contains this embedded type. Something like this:

query {
  bestAgent {
    first last
    profileImage {
      ... basicImageData
    }
  }
  bestHome {
    address
    streetImage {
      ... basicImageData
    }
  }
}
fragment basicImageData on ImageData {

  url
  dimensions {
    aspectRatio
  }
}

My idea is that since when using an embedded Schema (not a plain JS object) for reuse in mongoose the name of the type is anyway going to be wrong for any other types except for the first path that discovered this type - We might want to document the best way to force the name in advance.

Calling composeWithMongoose on the image model is not solving - I guess because it's not the same schema once you create a Model from it?

Calling something like this before all other composeWithMongoose:

convertSchemaToGraphQL(imageDataStructure, 'EmbeddedImage');

Would do the trick by placing a TC on the schema object _gqcTypeComposer prop - but does it feel like a hack?

Love to hear your thought.

rawQuery

I see that count, findOne and findMany can do rawQuery but I think findById does not process rawQuery. Can you please add rawQuery support to findById as well?

npm package tarball still contains wrong "dependencies" of mongoose and others.

Don't know how this weird thing happened since I can see the updated package.json in Github does not have "mongoose" in the "dependencies" section.
But when doing "npm view graphql-compose-mongoose" it is clear that the package.json in the registry still has this dependencies section:

 dependencies:
   { 'babel-runtime': '^6.20.0',
     'graphql-compose': '^1.7.0',
     'graphql-compose-connection': '^2.1.2',
     mongoose: '^4.7.4',
     'object-path': '^0.11.3' },

Not sure how critical this is but it caused some trouble for me - same is with graphql-compose which has graphql in it's dependencies section.
Probably has to do with how the package was updated in npm once those dependencies were converted to peer dependencies.

change field value after post mutation ?

hi ,

I want to change password with md5 or other hashing method
but I did not know how to set the modification resolver for mutation ?

my schema is

export const UserSchema = new Schema({
    name: String,
    username: {
        type: String,
        required: true,
        unique: true,
        trim: true,
        indexed: true
    },
    password: {
        type: String,
        required: true
    },
    email: {
        type: String,
        trim: true,
        unique: true,
        indexed: true
    },
    createdAt: Date,
    updatedAt: {
        type: Date,
        default: Date.now,
    }
}, {
  collection: 'users',
});


export const User = mongoose.model('User', UserSchema);
export const UserTC = composeWithRelay(composeWithMongoose(User));

I want when I make userCreate or userUpdate the password automatically hashed

Odd Resolution Name

I'm getting this

user(_id: MongoID!): EventPartyGuestProfile

When I am expecting this,

user(_id: MongoID!): UserAccount

Here's my sequence,

// user_account.js
export const UserAccountSchema = new mongoose.Schema(
 ...
);
export const UserAccount = mongoose.model('UserAccount', UserAccountSchema);

// user_account_type_composer.js
import { UserAccount } from '../schema/user_account';
const UserAccountTC = composeWithMongoose(UserAccount);
export default UserAccountTC;

// resolvers.js
import UserAccountTC from './user_account_type_composer';

export const queryFields = {
  user: UserAccountTC.getResolver('findById'),
  users: UserAccountTC.getResolver('findByIds'),
};

// 
import { ComposeStorage } from 'graphql-compose';
import moduleUserAccount from './user_account';

const GQC = new ComposeStorage();

GQC.rootQuery().addFields({
  ...moduleUserAccount.resolvers.queryFields
});

const schema = GQC.buildSchema();

At one point, I may have passed the wrong model name to composeWithMongoose function (
const UserAccountTC = composeWithMongoose(EventPartyGuestProfile) ), but changed the name and restarted the server several times since. I've also changed the name of the query fields with no problem. Where could this be coming from?

How to add a relation in a structured object ?

I've got a mongoose schema where the data are a bit more structured than usual :

const FixtureSchema = new Schema({
    day: { type: Number },
    idMpg: { type: String },
    home: {
        team: { type: Schema.Types.ObjectId, ref: "Team" },
        formation: { type: String },
        performances: [ { type: Schema.Types.ObjectId, ref: "Performance" }]
    },
    away: {
        team: { type: Schema.Types.ObjectId, ref: "Team" },
        formation: { type: String },
        performances: [ { type: Schema.Types.ObjectId, ref: "Performance" }]
    }
});

I tried to add a relation on home.team and away.team but I can do that as when I call the addRelation it complains about the dot. I could easily destructure the object replacing home.team by home_team and so on, but it would be a bit ugly. So what could I do to add my relation ?

Thanks,
Stéphane

Setting `false` on a resolver arg in typeConverterResolversOpts doesn't disable it

With the code:

const composeWithMongoose = require('graphql-compose-mongoose').composeWithMongoose
const User = require('../../../models/User')

const opts = {
  description: 'A user of the application.',
  resolvers: {
    findMany: {
      filter: false
    }
  }
}

module.exports = composeWithMongoose(User, opts)

...filter argument is still available on the findMany resolver. This code should disable it, no? Or am I understanding it wrong?

switch database :useDb()

I have been exploring various libraries for mongoose and graphql and this really looks promising.Great work guys .

I have a scenario where i need to switch database on the bases of request parameters is there any way i can replace the model object for every resolver using useDb function

I may be trying to find some thing which is already available in graphql-compose-mongoose

Enums

Whats the best way to define enums?

Relations and connections

Relations and connections



Created a Tweet model and installed a single link with User

import mongoose from 'mongoose'
import { UserTC } from './user'
import composeWithMongoose from 'graphql-compose-mongoose'
	

const TweetSchema = new mongoose.Schema({
	  text: String,
	  userId: {
	    type: mongoose.Schema.Types.ObjectId,
	    ref: 'User'
          }
}, { timestamps: true } )
	

export const Tweet = mongoose.model('Tweet', TweetSchema)
export const TweetTC = composeWithMongoose(Tweet)
	
TweetTC.addRelation(
	  'user',
	  {
	    resolver: () => UserTC.getResolver('findById'),
	    prepareArgs: {
	      _id: source => source.userId
	    },
	    projection: { userId: true },
	  }
)

Created a User model and installed a multiple link with Tweet

import mongoose from 'mongoose'
import { TweetTC } from './tweet'
import composeWithMongoose from 'graphql-compose-mongoose'
	
const UserSchema = new mongoose.Schema({
    username: {
	    type: String,
	    unique: true
	  },
	  firstName: String,
	  lastName: String,
	  avatar: String,
	  password: String,
	  email: String,
	  tweetsIds: [{
	    type: mongoose.Schema.Types.ObjectId,
	    ref: 'Tweet'
	  }],
}, { timestamps: true })

export const User = mongoose.model('User', UserSchema)
export const UserTC = composeWithMongoose(User)

UserTC.addRelation(
	  'tweets',
	  {
	    resolver: () => TweetTC.getResolver('findByIds'),
	    prepareArgs: {
	      _ids: (source) => source.tweetsIds || [],
	    },
	    projection: { tweetsIds: true },
	  }
)



I create a mutation where in the userId field I pass the users id

mutation {
  tweetCreate(record: {
    text: "Get tweet"
    userId: "5a0b3cde2c6afb534933fc5b"
  }) {
    recordId
  } 
}

As a result, the tweet was created

{
  "_id": ObjectId("5a0b47fcb4f0015a0d59b6d6"),
  "text": "Get tweet",
  "userId": ObjectId("5a0b3cde2c6afb534933fc5b"),
}

, but the array with the user's field tweetsIds is empty

 {
    "_id": "5a0b3cde2c6afb534933fc5b",
    "username": "sun",
    "tweetsIds": [],
},

The whole project lies here

Where am I mistaken?

Add default values from request

Hello!
I use your package to compose mongoose models to GraphQL and I have a mutation that creates new Goal record:

mutation createGoal($name:String!){
  goalCreate(record:{
    name: $name
  }){
    record {
      _id
       name
     }
   }
  }

Goal schema have an userId field (an id of user that created this Goal).

I don't want to pass userId from front-end due to security concern, but want to set userId in the back-end app, and get it from req.user object.

Is it possible to accomplish this with your library?
If it is, can you give me an example of how to set record field before original resolver is called?

To be more concise:
From front-end I send:

{
  "name": "New goal"
}

In the back-end I want to transform it to:

{
  "name": "New goal",
  "userId": "592e6eaac21d362f2d86039a"
}

where userId - the id of currently logged in user (req.user.id field).
And pass this transformed object to createOne resolver.

$in query in Relation

I might be missing something, but since this framework is so awesome I assume this should be somewhere in it, and I am missing where.
Given a model like this:

Model {
owners: [MongoID]
}

and


User {
  _id ....
}

I want to add a relation like this :

PlayerType.addRelation(
  // this should return all Models that have this _id in the Owner Array.
  "myData",
  () => ({
    resolver: ModelType.getResolver("findOne"), // Do I need a custom resolver that takes the id to check? 
    //***** What should be in the prepareArgs *****//
    projection: { _id: true }
  })
);

Do I need to roll my own resolver for this?

I am sorry if this is explained somewhere, but I did look and can't find anything that relates to this..

Do not call mongoose for findByIds with empty array argument

Hi,

I would assume, each call to the findByIds resolver with an empty array argument behaves just as if you pass no Array at all, it will always return the empty array []. If this assumptions holds true, we could add a new check to line 49 in the referred example, so we do not have to call mongoose.

https://github.com/nodkz/graphql-compose-mongoose/blob/4a854d2a44252d94d656b3b56ac2e2f47a44b71a/src/resolvers/findByIds.js#L46-L51

Any thoughts, objections?

Kind regards
Cedric

Connection in relation

Hello, first of all thank you for the good work. The graphql-comopose libraries are amazing and make life really easier !
I just have a question about making connection on a relation field.
Imagine I have User and Post schemas. A User has afield posts with the id of its posts.
How could I have a connection from the array of ids of the field posts in a relation. I mean something like this:

UserTC.addRelation(
  'friends',
  () => ({
    resolver: postTC.getResolver('connection'), // But I would like this connection to be from the array of id 
                                                                              contained in the field posts
    args: {
      _ids: (source) => source.posts,
    },
    projection: { posts: 1 }, // point fields in source object, which should be fetched from DB
  })
);

If you could help me doing this using your libraries it would be awesome !
Thanks in advance

Features: createMany, mutation for an existing array

hello~

Do we have plan to add createMany, and recordIds returns the array of ObjectIDs, records returns the updated objects.

//createMany
var array = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
Movies.insertMany(array, function(error, docs) {});

Could we support mutation for updating an array field if I pass an ObjectId that adding to the existing array instead of overwrite, the overwrite only happens if I pass an array of ObjectId?

The first mutation for phones and returns two values for phones being "111-222-333-444", "444-555-666-777".

mutation {
  userCreate(record: {
    contacts: {
      phones: [
        "111-222-333-444",
        "444-555-666-777"
      ]
    },
  }) {
    recordId
    record {
      contacts {
        email
        phones
      }
    }
  }
}

{
  "data": {
    "userCreate": {
      "recordId": "593ca1149f15dd003778ba1f",
      "record": {
        "contacts": {
          "email": null,
          "phones": [
            "111-222-333-444",
            "444-555-666-777"
          ]
        }
      }
    }
  }
}

The second mutation for phones, the expected returns are three values for phones being "111-222-333-444", "444-555-666-777", "444-555-666-888" instead of "444-555-666-888".

mutation {
  userCreate(record: {
    contacts: {
      phones: "444-555-666-888"
    },
  }) {
    recordId
    record {
      contacts {
        email
        phones
      }
    }
  }
}

{
  "data": {
    "userCreate": {
      "recordId": "593ca1149f15dd003778ba1f",
      "record": {
        "contacts": {
          "email": null,
          "phones": [
            "111-222-333-444",
            "444-555-666-777",
            "444-555-666-888"
          ]
        }
      }
    }
  }
}

thanks,
anderson

Allow integer _ids to work with findByIds?

Hi there. First up, nice work with this library - my team has been experimenting with it for our Graphql project and it has saved a lot of time.

We have just run into an issue with our primary key (_id) in some of our models. We are using an integer/number for _id rather than a MongoId. While this works with Model.getResolver('findById'), it doesn't work with Model.getResolver('findByIds).

I actually get a cast error when doing relations:

{ [CastError: Cast to number failed for value "00016cb0dd2f1e4b7df8d7bd" at path "_id"]
  message: 'Cast to number failed for value "00016cb0dd2f1e4b7df8d7bd" at path "_id"',
  name: 'CastError',
  kind: 'number',
  value: 00016cb0dd2f1e4b7df8d7bd,
  path: '_id',
  reason: undefined }

I've pinpointed the issue here:
https://github.com/nodkz/graphql-compose-mongoose/blob/master/src/resolvers/findByIds.js#L59-L60

It looks like there is a MongoId check on the id, and then it converts to a MongoId before being put into the selector query.

Is there a particular reason for this? Some flexibilty would be great - to my knowledge, Mongoose and Mongo have no issues with _id being an integer. Integers also work with findById so we assumed it would also work with findByIds.

Happy to submit a pull request, just wanted to check first :)

Many thanks
unkleho

Are Subscriptions supported?

Hi,

I found your graphql-compose-* family, and consider it very useful.
Really nice not having starting from scratch.

I am wondering if your graphql-compose-mongoose plugin supports subscriptions out of the box for mongoose models.

I found the GQC.rootSubscription() method, but did not see any example how to use it.

Many thanks in advance,
best regards.

How to use the in[] operator in query?

How do you use the in[] operator in a query? I can't figure out how to filter a findMany resolver to search by multiple values for a single field. Thanks!

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.