Reputation: 113
I am using Apollo-Server
and trying to create a REST query against the IEX REST API which returns back data that looks like this:
{
"symbol": "AAPL",
"companyName": "Apple Inc.",
"exchange": "Nasdaq Global Select",
"industry": "Computer Hardware",
"website": "http://www.apple.com",
"description": "Apple Inc is an American multinational technology company. It designs, manufactures, and markets mobile communication and media devices, personal computers, and portable digital music players.",
"CEO": "Timothy D. Cook",
"issueType": "cs",
"sector": "Technology",
"tags": [
"Technology",
"Consumer Electronics",
"Computer Hardware"
]
}
I am using datasources. My typeDefs
and resolvers
look something like this:
const typeDefs = gql`
type Query{
stock(symbol:String): Stock
}
type Stock {
companyName: String
exchange: String
industry: String
tags: String!
}
`;
const resolvers = {
Query:{
stock: async(root, {symbol}, {dataSources}) =>{
return dataSources.myApi.getSomeData(symbol)
}
}
};
The Datasource file looks like this:
class MyApiextends RESTDataSource{
constructor(){
super();
this.baseURL = 'https://api.iextrading.com/1.0';
}
async getSomeData(symbol){
return this.get(`/stock/${symbol}/company`)
}
}
module.exports = MyApi
I can run a query and get data back, but it is not formatting in an array and is throwing an error when I run a query like so:
query{
stock(symbol:"aapl"){
tags
}
}
Error:
{
"data": {
"stock": null
},
"errors": [
{
"message": "String cannot represent value: [\"Technology\", \"Consumer Electronics\", \"Computer Hardware\"]",
"locations": [
{
"line": 3,
"column": 5
}
],
"path": [
"stock",
"tags"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"TypeError: String cannot represent value: [\"Technology\", \"Consumer Electronics\", \"Computer Hardware\"]",
The data I am expecting (technology, consumer electronics, and computer hardware) are correct, but not returning in an array. I tried to make a new type
for tags, and set the it with a tag property, but the value just returns null
.
I am very new to graphql, so any feedback is appreciated!
Upvotes: 3
Views: 5077
Reputation: 84657
Inside your type definition for Stock
, you're defining the type for the tags
field as String!
:
tags: String!
That tells GraphQL to expect a String value that will not be null. The actual data being returned by the REST endpoint, however, is not a String -- it's an array of Strings. So your definition should minimally look like this:
tags: [String]
If you want GraphQL to throw if the tags value is null, add an exclamation point to the end to make it non-nullable:
tags: [String]!
If you want GraphQL to throw if any of the values inside the array are null, add an exclamation point inside the brackets. You can also combine the two:
tags: [String!]!
Upvotes: 5