How to change the graphql typedefs name that is coming from json results of external api? - graphql

I have encountered an issue with the naming in my typedefs. The error prompting the following.
Syntax Error: Expected Name, found Int "24"
I am using Coinmarketcap Api and accessing it with my apollo graphql server. The api has naming such as 24h_volume_usd, percent_change_1h etc, but as long as integer within the name, it will have this name issue.
I am not really sure how can I fix this issue. Can anyone please help me out? Thank you very much.
Schema.js:
const typeDefs = `
type cryptos {
id: String
name: String
symbol: String
rank: String
price_usd: String
price_btc: String
24h_volume_usd: String
market_cap_usd: String
percent_change_1h: String
available_supply: String
total_supply: String
last_updated: String
}
type Query {
cryptos: [cryptos]
}
`
resolvers.js:
const resolvers = {
Query: {
cryptos: () => {
return axios.get('https://api.coinmarketcap.com/v1/ticker/').
then(result => result.data );
}
}

Process api result using map functions
`var newHashmap = {};
Object.keys(hashmap).forEach(function(key){
var value = hashmap[key];
key = key + "xxx";
console.log("changing:");
console.log(key); newHashmap[key] = value
});`

Related

ApolloError: variable x is declared as '[String!]!', but used where '_text' is expected

ApolloError: variable 'wallet_addresses' is declared as '[String!]!', but used where '_text' is expected
I get that error above. And my query is below.
mutation updateUser(
$id: Int
$email: String
$wallet_addresses: [String!]!
) {
update_dev_user(
where: {email: {_eq: $email}}
_set: {
wallet_addresses: $wallet_addresses
}
){
returning {
id
email
}
}
}```
I believe the mistake is at the `$wallet_addresses: [String!]!` this part. I have no idea how I an define an array type in the parameter.
[![enter image description here](https://i.stack.imgur.com/aZcz9.png)](https://i.stack.imgur.com/aZcz9.png)
I tried
[String!]!
[String!]
[String]
[]
types but got errors in anyway and could find in the docs ( hasura ). I just want to send string array to a table column which has Text[] type.
I solved issue with giving type _text to wallet_addresses parameter and converted string array to array literal.
doc: https://hasura.io/docs/latest/mutations/postgres/insert/#insert-an-object-with-an-array-field
const toArrayLiteral = (arr: string[]) =>
JSON.stringify(arr)?.replace('[', '{')?.replace(']', '}')?.replaceAll('"', '');

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, ...
}
}

Conditional field in GraphQL Where query

Using Apollo client I am trying to run a query that will return students with any status if the status field is empty. If there is a status filter it should be applied:
const statusWhere = inputs.status ? { equals: $inputs.status }: {};
query GetStudents($course: ID, $status: String, $statusWhere: status_bool_exp) {
studentCourses (where :{
status: {$statusWhere},
course: {
id: {
equals: $course
}
},
# other fields, etc
This is giving error:
GraphQLError: Syntax Error: Expected Name, found "$".
Could you provide any hints?
After a bunch of trial and error I was able to figure it out myself. Posting it here because it could be useful for someone else.
Using the regular JS string interpolation variables works here.
So you need to define the condition as a string literal:
const statusWhere = inputs.status ? 'equals: "'+ inputs.status +'"' : '';
Then the whole gpl string looks like this:
gql`
query GetStudents($course: ID) {
studentCourses (where :{
status: {
${statusWhere}
},
course: {
id: {
equals: $course
}
},
})
# fields etc`
In this case you do not need to pass your string variable as a query param.

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

Why can I not remove an unused function from my Swift Class?

See the function 'postRequest' in this UserModel class I have defined. Well the function is not used anymore anywhere and when I try to remove it XCode syntax highlighting crashes and my program will not compile with a segmentation fault error 11 which points to nowhere.
I moved the function into a struct called SharedModel. So this function is not called anywhere! Why can I not remove it from the file? It makes no sense, I just want to remove an unused function. But Xcode keeps crashing and it makes me keep it! What is going on.
import Foundation
import SwiftHTTP
import SwiftyJSON
public enum UserProperties : String {
case user_id = "user_id", single_access_token = "single_access_token", first_name = "first_name",
last_name = "last_name", role = "role", email = "email", username = "username", barn_id = "barn_id",
location_id = "location_id", farm_id = "farm_id"
static let allValues = [user_id, single_access_token, first_name, last_name, role, email, username, barn_id, location_id, farm_id]
}
class UserModel {
var userPropertiesJSON: JSON?
init () {
}
func postRequest(url: String, params: Dictionary<String,AnyObject>, completionHandler: (JSON?) -> ()) {
var request = HTTPTask()
request.requestSerializer = JSONRequestSerializer()
//The expected response will be JSON and be converted to an object return by NSJSONSerialization instead of a NSData.
request.responseSerializer = JSONResponseSerializer()
//we have to add the explicit type, else the wrong type is inferred. See the vluxe.io article for more info.
//let params: Dictionary<String,AnyObject> = ["username": username, "password": password]
request.POST(url, parameters: params, success: {(response: HTTPResponse) in
println(response.responseObject!)
let json = JSON(response.responseObject!)
completionHandler(json)
},failure: {(error: NSError, response: HTTPResponse?) in
completionHandler(false)
})
}
func login(username: String, password: String, completionHandler: (Bool) -> ()) {
let params: Dictionary<String,AnyObject> = ["username": username, "password": password]
SharedModel.postRequest("http://farmcentral.softimum.com/user_sessions.json", params: params) { jsonOrError in
if let json: JSON = jsonOrError {
self.userPropertiesJSON = json
SharedModel.userPropertiesJSON = json
completionHandler(true)
} else {
completionHandler(false)
}
}
}
}
UPDATE
Still and issue but I have narrowed it down to the exact line of code that if removed causes xcode to crash and causes the build to stop compiling due to a segment fault 11 error.
This is the offending line: let json = JSON(response.responseObject!)
This line is in the function inside the closure. When I remove this line Xcode crashes. I am running cocoapods beta version, this might be a bug.
This was a bug with the framework I was using called SwiftyJSON. The solution was to import SwiftyJSON.swift file directly into your project.
Here is the Github issue: https://github.com/SwiftyJSON/SwiftyJSON/issues/67

Resources