How to create graphql-go *graphql.Schema from JavaScript string? - go

How to create graphql schema from string in Go?
This is my schema, here shown as a JavaScript string:
const schemaContent = `type Query {
greeting:String
students:[Student]
}
type Student {
id:ID!
firstName:String
lastName:String
password:String
collegeId:String
}`
How can I build from the schemaContent string a scheme of type schema *graphql.Schema in Go?

Related

GraphQLError: Syntax Error: Unexpected "("

I am new to GraphQL and am trying to query the TfL API for a project with React. I am trying to pass $arrival as a variable into the query, dynamically calling arrivals by station ID. It was working yesterday but this morning it is throwing a syntax error, any ideas where it may be coming from?
Type Defs
const typeDefs = `
type Station {
id: String!
stationName: String
lineId: String
lineName: String
platformName: String
direction: String
timestamp: String
timeToStation: Int
currentLocation: String
towards: String
expectedArrival: String
modeName: String
}
type Query($arrival: String!) {
getArrivals(id: $arrival): [Station]
station: [Station]
}
`;
Query
const GET_ALL_ARRIVALS = gql`
query Arrivals($id: String!) {
getArrivals(id: $id) {
id
stationName
platformName
lineName
towards
timeToStation
}
}
`;
Try changing your schema to
const typeDefs = `
type Station {
id: String!
stationName: String
lineId: String
lineName: String
platformName: String
direction: String
timestamp: String
timeToStation: Int
currentLocation: String
towards: String
expectedArrival: String
modeName: String
}
type Query {
getArrivals(id: String!): [Station]
station: [Station]
}
`;
That doesn't explain the error, but it seems wrong to me in comparison to the documentation
When you declare the top-level query type, you're trying to embed variable definitions as part of the type definition. They don't belong here; they are purely part of the query. $variable references never appear anywhere in the schema.
type Query { # does not take any parameters
getArrivals(id: ID!): [Station]
# ^^^ specify the _type_ of the field argument here
}
query Arrivals($someId: ID!) { # variable definition is part of the query
getArrivals(id: $someId) { # bind variable to field argument
id, ...
}
}

Graphql object ( or JSON) as filter argument

Is it possible to have a JSON object as filed in filter arguments. Something like:
Query{
building(location:{lon,lat}){
name,...
}
}
I need to pass location, and I would like to pass it as js object ( to apollo client) or as stringified JSON.
You can use input types to achieve that. You need to edit your schema
type Query {
building(location: Location): Building
}
input Location {
lon: String
lat: String
}
Then you can post your query like this
query {
building(location: {lon:"100.332680",lat:"5.416393"}) {
name,...
}
}

My struct is not encoding correctly and is missing a property

type ApiResponse struct {
Success bool `json:"success"`
Errors []string `json:"errors"`
}
type NewSessionResponse struct {
ApiResponse `json:"apiResponse"`
authToken string `json:"authToken"`
}
In my handler I am doing this:
resp := NewSessionResponse{ApiResponse{true, []string{}}, "auth123"}
json.NewEncoder(w).Encode(resp)
The response I am seeing is this:
{
apiResponse: {
success: true,
errors: [ ]
}
}
Why isn't my authToken property in the JSON result?
authToken filed is an unexported field. Json library does not have the power to view fields using reflect unless they are exported. A package can only view the unexported fields of types within its own package.
You can export the filed to get this working
type NewSessionResponse struct {
ApiResponse `json:"apiResponse"`
AuthToken string `json:"authToken"`
}
FYI: Exported identifiers https://golang.org/ref/spec#Exported_identifiers

How to pass GraphQLEnumType in mutation as a string value

I have following GraphQLEnumType
const PackagingUnitType = new GraphQLEnumType({
name: 'PackagingUnit',
description: '',
values: {
Carton: { value: 'Carton' },
Stack: { value: 'Stack' },
},
});
On a mutation query if i pass PackagingUnit value as Carton (without quotes) it works. But If i pass as string 'Carton' it throws following error
In field "packagingUnit": Expected type "PackagingUnit", found "Carton"
Is there a way to pass the enum as a string from client side?
EDIT:
I have a form in my front end, where i collect the PackagingUnit type from user along with other fields. PackagingUnit type is represented as a string in front end (not the graphQL Enum type), Since i am not using Apollo Client or Relay, i had to construct the graphQL query string by myself.
Right now i am collecting the form data as JSON and then do JSON.stringify() and then remove the double Quotes on properties to get the final graphQL compatible query.
eg. my form has two fields packagingUnitType (An GraphQLEnumType) and noOfUnits (An GraphQLFloat)
my json structure is
{
packagingUnitType: "Carton",
noOfUnits: 10
}
convert this to string using JSON.stringify()
'{"packagingUnitType":"Carton","noOfUnits":10}'
And then remove the doubleQuotes on properties
{packagingUnitType:"Carton",noOfUnits:10}
Now this can be passed to the graphQL server like
newStackMutation(input: {packagingUnitType:"Carton", noOfUnits:10}) {
...
}
This works only if the enum value does not have any quotes. like below
newStackMutation(input: {packagingUnitType:Carton, noOfUnits:10}) {
...
}
Thanks
GraphQL queries can accept variables. This will be easier for you, as you will not have to do some tricky string-concatenation.
I suppose you use GraphQLHttp - or similar. To send your variables along the query, send a JSON body with a query key and a variables key:
// JSON body
{
"query": "query MyQuery { ... }",
"variables": {
"variable1": ...,
}
}
The query syntax is:
query MyMutation($input: NewStackMutationInput) {
newStackMutation(input: $input) {
...
}
}
And then, you can pass your variable as:
{
"input": {
"packagingUnitType": "Carton",
"noOfUnits": 10
}
}
GraphQL will understand packagingUnitType is an Enum type and will do the conversion for you.

How to return nested objects in GraphQL schema language

I was going through the documentation for GraphQl and realized that the new Schema Langugage supports only default resolvers. Is there a way I can add custom resolvers while using the new Schema Language?
let userObj = {
id: 1,
name: "A",
homeAddress: {
line1: "Line1",
line2: "Line2",
city: "City"
}
};
let schema = buildSchema(`
type Query {
user(id: ID): User
}
type User {
id: ID
name: String
address: String
}
`);
//I would like User.address to be resolved from the fields in the json response eg. address = Line1, Line2, City
This is the schema that I have defined. I would like to add some behavior here that would allow me to parse the address object and return a concatenated string value.
As mentioned by HagaiCo and in this github issue, the right way would be to go with graphql-tools.
It has a function called makeExecutableSchema, which takes a schema and resolve functions, and then returns an executable schema
It seems like you have a confusion in here, since you defined that address is String but you send a dictionary to resolve it.
what you can do, is to define a scalar address type:
scalar AddressType if you use buildSchema and then attach parse functions to it. (or use graphql-tools to do it easily)
or build the type from scratch like shown in the official documentations:
var OddType = new GraphQLScalarType({
name: 'Odd',
serialize: oddValue,
parseValue: oddValue,
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return oddValue(parseInt(ast.value, 10));
}
return null;
}
});
function oddValue(value) {
return value % 2 === 1 ? value : null;
}
and then you can parse the dictionary into a string (parseValue) and otherwise

Resources