Skip to content

Instantly share code, notes, and snippets.

@nodkz
Last active March 30, 2016 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nodkz/164f410c78d7a8f01a0d to your computer and use it in GitHub Desktop.
Save nodkz/164f410c78d7a8f01a0d to your computer and use it in GitHub Desktop.
Schema configuration example for commit "Create schema2.js for getting more granular schema configuration" (https://github.com/nodkz/graffiti-mongoose/commit/08aa4a394c8b53a442ec05929f1b0035418a1ae0).
// This gist is a draft solution for extending graphQL schemas generated by graffiti.
import { getSchema, addMongooseModel, getGQType, getExistedType } from 'lib/graffiti-mongoose/src/schema/schema2';
import { User } from 'app/_schema/mongoose/user';
import { Cv } from 'app/_schema/mongoose/cv';
import { UserData } from 'app/_schema/mongoose/userData';
import ExtraFieldsWrapper from 'lib/graffiti-mongoose/src/wrappers/extra-fields';
import getFieldList from 'lib/graffiti-mongoose/src/query/projection';
addMongooseModel(User);
// add mongoose model `UserData` to graffiti-models cache.
// Second param `false` said that this model should not be resolved in the root queries.
addMongooseModel(UserData, false);
let CvWrapped = Cv;
// This is graffiti wrapper for mongoose model, which add one more field `userData` to `Cv` type in graphql.
CvWrapped = new ExtraFieldsWrapper(CvWrapped, {
extraFields: {
userData: {
type: getGQType(UserData), // this is gq type generator from mongoose model, which was added to graffiti model cache
description: 'Current user data for this object',
resolve(obj, args, ast) {
const userId = '56fa846b47c6c2be5bee528a';
return UserDataByRef.findByUser(userId).select(getFieldList(ast)).limit(1).then(
(result) => {
if (result && result[0]) {
return {
...result[0].toObject(),
_type: UserDataByRef.modelName,
};
}
return null;
}
);
},
},
},
});
const UserDataInterface = new GraphQLInterfaceType({
name: 'UserDatable',
description: 'An object with user data (fav, notes, etc)',
fields: () => ({
userData: {
type: getGQType(UserData),
description: 'Current user data (fav, notes) for this object',
},
}),
resolveType: (obj) => (obj._type ? getExistedType(obj._type) : null),
});
// wrapper for adding interfaces
CvWrapped = new ExtraInterfacesWrapper(CvWrapped, { extraInterfaces: [UserDataInterface] });
// after wrapping mongoose model `Cv` we add it to graffiti models
addMongooseModel(CvWrapped);
// getSchema accept only options, because internally use models which was added via `addMongooseModel(MongooseModel, true);`
const Schema = getSchema();
export default Schema;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment