smooth-code / graphql-directive Goto Github PK
View Code? Open in Web Editor NEWUse custom directives in your GraphQL schema and queries ๐ฉ
License: MIT License
Use custom directives in your GraphQL schema and queries ๐ฉ
License: MIT License
Hi, just saw you PR to fix Apollos InMemoryCache to support custom directives, which landed in the master is part of the actual code base.
I am using ApolloClient and would like to implement a custom directive on the client side.
I would really appreciate, if you could drop in an example here, how you would implement the simplest directive for ApolloClient? Or maybe a hint where to look it up. I found only some ServerSide examples, and I am bit confused about the client side part. Thank you
I've noticed some issues if I'm using this with the latest graphql
(0.12.3). If I try using it on a schema, the first error I get is:
Uncaught TypeError: Cannot read property 'FIELD_DEFINITION' of undefined
Which is coming from here. It seems that the latest graphql
has updated some of the object mappings. (Seems like there are a lot of updates to the schema in 0.12.)
Hi guys. I'm trying to implement my custom directives, and this package makes process so easy, but I've discovered that it breaks default behavior of @inclue
and @skip
Lets' take simple start app, from graphql-server-example. Change code little bit, and when I wrap schema with custom directive resolvers using addDirectiveResolveFunctionsToSchema
, it breaks @skip(if: false)
and @include(if: true)
, while @include(if: false)
and @skip(if: true)
still work.
const { ApolloServer, gql } = require('apollo-server')
const { addDirectiveResolveFunctionsToSchema } = require('graphql-directive')
const { makeExecutableSchema } = require('graphql-tools')
// This is a (sample) collection of books we'll be able to query
// the GraphQL server for. A more complete example might fetch
// from an existing data source like a REST API or database.
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
]
// Type definitions define the "shape" of your data and specify
// which ways the data can be fetched from the GraphQL server.
const typeDefs = gql`
directive @upper on FIELD | FIELD_DEFINITION
# Comments in GraphQL are defined with the hash (#) symbol.
# This "Book" type can be used in other type declarations.
type Book {
title: String
author: String
}
# The "Query" type is the root of all GraphQL queries.
# (A "Mutation" type will be covered later on.)
type Query {
books: [Book]
}
`
// Resolvers define the technique for fetching the types in the
// schema. We'll retrieve books from the "books" array above.
const resolvers = {
Query: {
books: () => books,
},
}
const directiveResolvers = {
async upper (resolve, source, args, { locale }) {
const value = await resolve()
if (typeof value === 'string') {
return value.toUpperCase()
}
return value
},
}
const schema = makeExecutableSchema({
typeDefs,
resolvers,
})
addDirectiveResolveFunctionsToSchema(schema, directiveResolvers)
// In the most basic sense, the ApolloServer can be started
// by passing type definitions (typeDefs) and the resolvers
// responsible for fetching the data for those types.
const server = new ApolloServer({
schema,
engine: process.env.ENGINE_API_KEY && {
apiKey: process.env.ENGINE_API_KEY,
},
})
// This `listen` method launches a web-server. Existing apps
// can utilize middleware options, which we'll discuss later.
server.listen().then(({ url }) => {
console.log(`๐ Server ready at ${url}`)
})
It throw error
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"TypeError: directiveInfo.resolver is not a function",
...
Do I miss something?
Thanks.
I added a new "directive" called "export". To use these directive values hold in memory. But I need one more "directive" to use these values. I named it "import". I want to do something like this. Is something like this possible. Is there a way to use "directive" in the Argument?
query{
users(name: "Test"){
user_id @export(as: "user_id")
}
safe(user_id: @import(name: "user_id")){
safe_id
name
}
}
Could you create an example using graphql-tools makeExecutableSchema
and existing resolvers?
It's not totally clear how to do it.
I'm trying to implement a live directive, which keeps the caller of the query up-to-date.
This is my current code, which does just resolve()
with the directive.
const typeDefs = /* GraphQL */ `
directive @live on FIELD | FIELD_DEFINITION
type Todo {
text: String!
completed: Boolean!
}
type Query {
allTodos: [Todo]! @live
}
`;
const resolvers = {
Query: {
allTodos() {
return someTodoArray;
}
}
};
const executableSchema = makeExecutableSchema({
typeDefs,
resolvers
});
addDirectiveResolveFunctionsToSchema(executableSchema, {
live(resolve) {
return resolve();
}
});
How would I push new results to the caller with this approach?
Is there a way to get a reference to the caller to push new results?
so i have directive with variables
directive @url(root: String!) on FIELD
with simple resolver:
async url(resolve, source, directiveArgs) {
return url.resolve(directiveArgs.root, await resolve())
},
so it should work with query variables binding like that
query($url: String!) { foo @url(root:$url) }
Hi, is it possible to add directives for types/fields using GraphQLObjectType instead of SDL? Is it supported? I could only see examples using SDL. Thanks.
Hi, it throws me the following error when trying to add directive resolve functions to the schema.
I have checked with forEachField and astNode is always undefined, is it my configuration or is it a bug?
const schema = new GraphQLSchema({
directives: [
new GraphQLDirective({
name: 'isAuth',
locations: [ DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.FIELD ]
})
],
query: new GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: new GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: GraphQLNonNull(GraphQLInt) },
email: { type: GraphQLNonNull(GraphQLString) }
})
}),
args: { id: { type: GraphQLInt } },
resolve: (parent, args, context, info) => {
return { id: 1, email: '[email protected]' };
}
}
}
})
});
const directiveResolvers = {
isAuth(next, source, args, context, info) {
throw Error('Ups!');
}
};
const { addDirectiveResolveFunctionsToSchema } = require('graphql-directive');
addDirectiveResolveFunctionsToSchema(schema, directiveResolvers);
When will this be supported?
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.