@ryleigh
In Nest.js, you can access the field name in GraphQL by using the resolver function that corresponds to the field.
To access the field name in Nest.js, you can use the @Resolver()
decorator to define a resolver class for your schema, and then create resolver functions that correspond to each field in your schema.
For example, if you have a schema with a field named username
, you can create a resolver function like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { Resolver, Query, Field, ObjectType } from '@nestjs/graphql'; @ObjectType() class User { @Field() username: string; } @Resolver(of => User) class UserResolver { @Query(returns => User) getUser() { return { username: 'john_doe' // replace with username from database }; } } |
In the resolver function getUser()
, you can access the field name username
by simply referencing it in the return object or by accessing it from the database or any other data source you are using.
You can also access the field name within the resolver function using the arguments provided by the function, such as parent
, args
, context
, and info
. The info
argument in particular contains information about the query being executed, including the field name.
1 2 3 4 5 6 7 8 9 10 |
@Resolver(of => User) class UserResolver { @Query(returns => User) getUser(parent, args, context, info) { console.log(info.fieldName); // Access the field name return { username: 'john_doe' // replace with username from database }; } } |
By using the info.fieldName
property, you can access the field name within the resolver function and perform any necessary actions based on that field name.