Comments (14)
@Sandreu I made a library that expands on the example above and includes handling for skip and include directives: graphql-list-fields
from graphql-js.
I suppose the short answer is that you cannot directly get to a fragment from a field AST. There must also be a mapping of fragment name to the fragment AST.
Could you help me understand how you're using the fields and in what context you need access to the fragment definitions? Is this from within a field resolve function?
from graphql-js.
@leebyron thank you for the quick answer!
Yes, but I'm using this from query resolve function, not field resolve. Currently I'm working on mapping fieldASTs to MongoDB projections. I've done with the Field and InlineFragment, now I want to get FragmentSpread working to complete common cases of GraphQL queries.
from graphql-js.
Could you link me to the point in your code where this is being used? I'm afraid I don't know what you mean by "query resolve function"
from graphql-js.
@leebyron consider this
const todoQueries = {
todo: {
type: todoType,
args: {
_id: {
name: '_id',
type: new GraphQLNonNull(GraphQLString),
},
},
resolve: (root, { _id }, source, fieldASTs) => {
const projs = getProjection(fieldASTs);
return Todo.findById(_id, projs);
},
}
};
Queries here are part of GraphQL schema. And I'm working on getProjection
function. Currently it is as follows:
function getProjection(fieldASTs) {
const { selections } = fieldASTs.selectionSet;
return selections.reduce((projs, selection) => {
switch (selection.kind) {
case 'Field':
return {
...projs,
[selection.name.value]: 1
};
case 'InlineFragment':
return {
...projs,
...getProjection(selection),
};
default:
throw 'Unsupported query';
}
}, {});
}
from graphql-js.
@leebyron hi! The use case is that in graffiti-mongoose we are doing some kind of field selection (projection) with Mongoose to optimise our queries to get only the necessary data from the database.
Our issue is that currently we cannot get the required fields from graphql-js
's fieldASTs
if the selection.kind
is FragmentSpread
. (we can if it's Field
or InlineFragment
)
Details:
The projection in mongoose looks like this:
Model.find({ age: 26 }, { name: 1, createdAt: 1 })
so the second parameter is the field selection.
For example from this query:
query GetUser {
user(_id: 1) {
...UserFragment
foo
}
}
fragment UserFragment on User {
name
}
we would like to generate the projection object below:
{
name: 1,
foo: 1
}
But currently we cannot read the selection fields from the selection if it's FragmentSpread
.
The current workaround is that if the query contains fragment we don't do any projection and get all of the fields from the database:
RisingStack/graffiti-mongoose@25fc49c#diff-2169c493dbfb064f0cf8f5c05d6fffadR17
Any idea how can we read the required fields from FragmentSpread
selection?
I'm happy to send pull-request to graphql-js
but I'm not sure yet that it's an issue here or am I doing something wrong.
from graphql-js.
This is now solved by #119 which should be released on npm soon.
from graphql-js.
@leebyron thanks!
from graphql-js.
Hello,
Sorry to reopen this ticket, but it seems that nobody kept going with this... I need the same thing, and here is the update of @gyzerok 's code to deal with the current version :
export default function getFieldList(asts) {
//for recursion...Fragments don't have many sets...
if (!Array.isArray(asts)) asts = [asts]
//get all selectionSets
var selections = asts.reduce((selections, source) => {
selections.push(...source.selectionSet.selections);
return selections;
}, []);
//return fields
return selections.reduce((list, ast) => {
switch (ast.kind) {
case 'Field' :
list[ast.name.value] = true
return list;
case 'InlineFragment':
return {
...list,
...getFieldList(ast)
};
case 'FragmentSpread':
console.log(ast)
default:
throw new Error('Unsuported query selection')
}
}, {})
}
It appears that Fieds are seen wherever they are declared, but selectionSets of FragmentSpread are not declared.
log output :
{
kind: 'FragmentSpread',
name: [Object],
directives: [],
loc: [Object]
}
from graphql-js.
Ok, I got it...
When parent's resolve is called, we don't know yet which children fields will be included! and directives aren't solved yet... When executor calls resolve, it's blind about what's next... the resolve would be called even if directives skip all children...!
The above getFieldList function could work like this :
export default function getFieldList(context, asts = context.fieldASTs) {
//for recursion...Fragments doesn't have many sets...
if (!Array.isArray(asts)) asts = [asts]
//get all selectionSets
var selections = asts.reduce((selections, source) => {
selections.push(...source.selectionSet.selections);
return selections;
}, []);
//return fields
return selections.reduce((list, ast) => {
switch (ast.kind) {
case 'Field' :
list[ast.name.value] = true
return list;
case 'InlineFragment':
return {
...list,
...getFieldList(context, ast)
};
case 'FragmentSpread':
return {
...list,
...getFieldList(context, context.fragments[ast.name.value])
};
default:
throw new Error('Unsuported query selection')
}
}, {})
}
But in fact, it doesn't really get the child list because directives are ignored... They are solved later by GQL...
I don't really know what to say about this...
What do you think ? @leebyron @dschafer @schrockn
from graphql-js.
@Sandreu can you explain the above a bit more? I'm seeing this with 0.4.4 for the first example query in this thread:
{ kind: 'FragmentDefinition',
name:
{ kind: 'Name',
value: 'TextFragment',
loc: { start: 115, end: 127, source: [Object] } },
typeCondition:
{ kind: 'NamedType',
name: { kind: 'Name', value: 'Todo', loc: [Object] },
loc: { start: 131, end: 135, source: [Object] } },
directives: [],
selectionSet:
{ kind: 'SelectionSet',
selections: [ [Object] ],
loc: { start: 136, end: 150, source: [Object] } },
loc:
{ start: 106,
end: 150,
source:
Source {
body: <Buffer 20 71 75 65 72 79 20 51 75 65 72 79 57 69 74 68 46 72 61 67 6d 65 6e 74 20 7b 0a 20 20 20 20 74 6f 64 6f 28 5f 69 64 3a 20 22 35 35 61 36 32 34 62 61 ... >,
name: 'GraphQL' } } }
and the selectionSet.selections from above:
[ { kind: 'Field',
alias: null,
name: { kind: 'Name', value: 'text', loc: [Object] },
arguments: [],
directives: [],
selectionSet: null,
loc: { start: 142, end: 146, source: [Object] } } ]
This looks like we have everything we need?
from graphql-js.
Hello @parkan ,
I'm not quite sure that I'm getting your question right,
But I think that is because you're looking into the text resolver... The aim here is to get the list of children fields from the parent resolver. Not a list of locations where the resolving field is requested.
Here is a complete example...
import gql, {
graphql,
GraphQLString,
GraphQLSchema,
GraphQLObjectType,
} from './src';
var test = new GraphQLObjectType({
name: 'Test',
fields: () => ({
a : { type: GraphQLString, },
b : { type: GraphQLString, },
c : { type: GraphQLString, },
})
});
var Queries = new GraphQLObjectType({
name: 'Query',
fields: () => ({
req: {
type: test,
resolve: (_, inputs, context) => {
console.log(getFieldList(context));
/*********************************
{ a: true, b: true, c: true }
*********************************/
// Here is your request with fields selection !
return { a:'a', b:'b', c:'c'}
}
}
}),
});
var Schema = new GraphQLSchema({
query: Queries,
});
function getFieldList(context, asts = context.fieldASTs) {
//for recursion...Fragments doesn't have many sets...
if (!Array.isArray(asts)) asts = [asts]
//get all selectionSets
var selections = asts.reduce((selections, source) => {
selections.push(...source.selectionSet.selections);
return selections;
}, []);
//return fields
return selections.reduce((list, ast) => {
switch (ast.kind) {
case 'Field' :
list[ast.name.value] = true
return list;
case 'InlineFragment':
return {
...list,
...getFieldList(context, ast)
};
case 'FragmentSpread':
console.log(ast)
/**********************
{ kind: 'FragmentSpread',
name: [Object],
directives: [],
loc: [Object] }
*************************/
return {
...list,
...getFieldList(context, context.fragments[ast.name.value])
};
default:
throw new Error('Unsuported query selection')
}
}, {})
}
graphql(Schema, '{ req { a, ...f } } fragment f on Test { b, c }');
As you can see here, the FragmentSpread
does not includes selectionSet
and then you have to go through context.fragments.
I gave up on querying my db only the requested fields so I don't really know about corner cases with this getFields function
! But I'm sure it doesn't handle directives...
graphql(Schema, '{ req { a, ...f @skip(if:true) } } fragment f on Test { b, c }')
Here getFields
will return { a: true, b: true, c: true }
event if the answer will include a
only...
from graphql-js.
@Sandreu I am facing the same issue. Did you find the solution?
from graphql-js.
@ansarizafar A solution about what ? Getting the requested fields works with this getFieldList()
function, I'm just preventing about corner cases like skip directives usage...
from graphql-js.
Related Issues (20)
- Collection of libraries and how they import from `graphql` HOT 20
- `process.env`, `globalThis`, and `typeof process` HOT 22
- Introspection queries don't support `@oneOf` HOT 2
- Tutorial data HOT 2
- astFromValue fails with a custom scalar serializing to an object value HOT 5
- In a response to a query about an Issue, the URL and other info is missing for links created with Reference editor button HOT 5
- author/committer -> user fields returning NULL for commits committed by user
- [email protected]
- npm link with graphql package breaks application HOT 2
- IHeyReally.com HOT 1
- Can I ask what is the progress here? Is there a solution being worked on? Do we have some timeline? Or progress with issue? Thanks!
- IHeyReally.com
- Typescript error with 16.9.0 (re ThunkObjMap) HOT 3
- Notice: default branch is now `16.x.x` HOT 3
- <a href="https://api.easycla.lfx.linuxfoundation.org/v2/repository-provider/github/sign/12261526/38307428/4135/#/?version=2"><img src="https://s3.amazonaws.com/cla-project-logo-prod/cla-not-signed.svg" alt="CLA Not Signed" align="left" height="28" width="328"></a><br/><br /><ul><li><a href='https://api.easycla.lfx.linuxfoundation.org/v2/repository-provider/github/sign/12261526/38307428/4135/#/?version=2' target='_blank'>:x:</a> - login: @Heyitsquoracom / name: [email protected] . The commit (b6081f914f0c5c22ee48d26aff4b473bf17627ce) is not authorized under a signed CLA. <a href='https://api.easycla.lfx.linuxfoundation.org/v2/repository-provider/github/sign/12261526/38307428/4135/#/?version=2' target='_blank'>Please click here to be authorized</a>. For further assistance with EasyCLA, <a href='https://jira.linuxfoundation.org/servicedesk/customer/portal/4' target='_blank'>please submit a support request ticket</a>.</li></ul><!-- Date Modified: 2024-06-28 04:40:51.630768 -->
- Error with version v16.9.0: `Can't resolve '@apollo/subgraph/dist/directives''` HOT 1
- Type is incorrect in graphql ExecutionResult with new type GraphQLFormattedError HOT 1
- [email protected]
- Allow to call `resolveType` outside of `execute` context HOT 1
- Add Query to Fetch All Messages HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from graphql-js.