How to get field value having space, hyphen in REST API in GraphQL - graphql

REST API Endpoint - https://api.jikan.moe/v3/manga/13
"Alterantive version", "Side story" and "Spin-off" fields are having space and hyphen.
common_schema.js
const { gql } = require('apollo-server');
const typeDefs = gql`
type RelatedType {
Adaptation: [RelatedSubType]
SideStory: [RelatedSubType]
Character: [RelatedSubType]
Summary: [RelatedSubType]
Other: [RelatedSubType]
AlternativeVersion: [RelatedSubType]
SpinOff: [RelatedSubType]
}
type RelatedSubType {
mal_id: ID
type: String
name: String
url: String
}
`;
module.exports = typeDefs;
If I write field value as Spin-off or Alternative version then it gives an error in terminal. "Spin-off" also doesn't work. I know these aren't valid but then also tried.
manga_resolver.js
module.exports = {
Query: {
manga: (_, { id }, { dataSources }) =>
dataSources.mangaAPI.getMangaDetail(id)
}
};
manga.js
const { RESTDataSource } = require('apollo-datasource-rest');
class MangaAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://api.jikan.moe/v3/manga/';
}
async getMangaDetail(mal_id) {
const response = await this.get(`/${mal_id}`);
return response;
}
}
module.exports = MangaAPI;
Query -
query getMangaDetail{
manga(id: 13){
related{
Adaptation{
name
}
AlternativeVersion{
name
}
SpinOff{
name
}
}
}
}
Getting null in those fields which are having space and hyphen.
Query result -
{
"data": {
"manga": {
"related": {
"Adaptation": [
{
"name": "One Piece"
}
],
"AlternativeVersion": null,
"SpinOff": null
}
}
}
}
Repository - jikan-graphql

According to the spec, names in GraphQL must follow this format:
/[_A-Za-z][_0-9A-Za-z]*/
In other words, neither spaces nor dashes are permitted. If your data source is returning property names that are formatted incorrectly, you can just provide resolvers for the fields in question:
const resolvers = {
RelatedType: {
sideStory: (parent) => {
return parent['Side story']
},
...
}
}

Related

WpGraphQL query returns null

I'm having this GraphQL query from headless Wordpress in Nexjs via WpGraphQl plugin:
export const GET_POSTS_BY_CATEGORY_SLUG = gql`
query GET_POSTS_BY_CATEGORY_SLUG( $slug: String, $uri: String, $perPage: Int, $offset: Int ) {
${HeaderFooter}
page: pageBy(uri: $uri) {
id
title
content
slug
uri
seo {
...SeoFragment
}
}
categories(where: {slug: $slug}) {
edges {
node {
slug
posts: posts(where: { offsetPagination: { size: $perPage, offset: $offset }}) {
edges {
node {
id
title
excerpt
slug
featuredImage {
node {
...ImageFragment
}
}
}
}
pageInfo {
offsetPagination {
total
}
}
}
}
}
}
}
${MenuFragment}
${ImageFragment}
${SeoFragment}
`;
And this is my getStaticProps function:
export async function getStaticProps(context) {
const { data: category_IDD } = await client.query({
query: GET_POSTS_BY_CATEGORY_SLUG,
});
const defaultProps = {
props: {
cat_test: JSON.parse(JSON.stringify([category_IDD])),
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}
If i pass it like this in props:
const defaultProps = {
props: {
cat_test: category_IDD,
},
i get an error saying:
SerializableError: Error serializing `.cat_test` returned from `getStaticProps` in "/category/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
But when i JSON.parse as the code above, i get null
Whats wrong with this query?
Just noticed that the $slug is an array of strings, so here should be:
query GET_POSTS_BY_CATEGORY_SLUG( $slug: [String], $uri: String, $perPage: Int, $offset: Int )
instead of $slug: String
You're not actually passing the $slug variable to the query.
For instance if your page route is /category/[slug].js your getStaticProps should look something like this.
export async function getStaticProps(context) {
const { slug } = context.params;
const { data: category_IDD } = await client.query({
query: GET_POSTS_BY_CATEGORY_SLUG,
variables: { slug },
});
const defaultProps = {
props: {
cat_test: JSON.parse(JSON.stringify([category_IDD])),
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}

GraphQL Subscriptions return an empty (null) response [duplicate]

I have the following GRAPHQL subscription:
Schema.graphql
type Subscription {
booking: SubscriptionData
}
type SubscriptionData {
booking: Booking!
action: String
}
And this is the resolver subsrciption file
Resolver/Subscription.js
const Subscription = {
booking: {
subscribe(parent, args, { pubsub }, info) {
return pubsub.asyncIterator("booking");
}
}
};
export default Subscription;
Then I have the following code on the Mutation in question
pubsub.publish("booking", { booking: { booking }, action: "test" });
I have the follow subscription file in front end (React)
const getAllBookings = gql`
query {
bookings {
time
durationMin
payed
selected
activity {
name
}
}
}
`;
const getAllBookingsInitial = {
query: gql`
query {
bookings {
time
durationMin
payed
selected
activity {
name
}
}
}
`
};
class AllBookings extends Component {
state = { allBookings: [] }
componentWillMount() {
console.log('componentWillMount inside AllBookings.js')
client.query(getAllBookingsInitial).then(res => this.setState({ allBookings: res.data.bookings })).catch(err => console.log("an error occurred: ", err));
}
componentDidMount() {
console.log(this.props.getAllBookingsQuery)
this.createBookingsSubscription = this.props.getAllBookingsQuery.subscribeToMore(
{
document: gql`
subscription {
booking {
booking {
time
durationMin
payed
selected
activity {
name
}
}
action
}
}
`,
updateQuery: async (prevState, { subscriptionData }) => {
console.log('subscriptionData', subscriptionData)
const newBooking = subscriptionData.data.booking.booking;
const newState = [...this.state.allBookings, newBooking]
this.setState((prevState) => ({ allBookings: [...prevState.allBookings, newBooking] }))
this.props.setAllBookings(newState);
}
},
err => console.error(err)
);
}
render() {
return null;
}
}
export default graphql(getAllBookings, { name: "getAllBookingsQuery" })(
AllBookings
);
And I get the following response:
data: {
booking: {booking: {...} action: null}}
I get that I am probably setting up the subscription wrong somehow but I don't see the issue.
Based on your schema, the desired data returned should look like this:
{
"booking": {
"booking": {
...
},
"action": "test"
}
}
The first booking is the field on Subscription, while the second booking is the field on SubscriptionData. The object you pass to publish should have this same shape (i.e. it should always include the root-level subscription field).
pubsub.publish('booking', {
booking: {
booking,
action: 'test',
},
})

Nested query and mutation in type-Graphql

I found a feature in graphql to write nested query and mutation, I tried it but got null. I found the best practices of building graphqL schema on Meetup HolyJs and the speaker told that one of the best ways is building "Namespaced" mutations/queries nested, in this way you can write some middlewares inside the "Namespaced" mutations/queries and for get the Child mutation you should return an empty array because if you return an empty array, Graphql understand it and go one level deep.
Please check the example code.
Example in graphql-tools
const typeDefs = gql`
type Query { ...}
type Post { ... }
type Mutation {
likePost(id: Int!): LikePostPayload
}
type LikePostPayload {
recordId: Int
record: Post
# ✨✨✨ magic – add 'query' field with 'Query' root-type
query: Query!
}
`;
const resolvers = {
Mutation: {
likePost: async (_, { id }, context) => {
const post = await context.DB.Post.find(id);
post.like();
return {
record: post,
recordId: post.id,
query: {}, // ✨✨✨ magic - just return empty Object
};
},
}
};
This is my Code
types
import { ObjectType, Field } from "type-graphql";
import { MeTypes } from "../User/Me/Me.types";
#ObjectType()
export class MeNameSpaceTypes {
#Field()
hello: string;
#Field({ nullable: true })
meCheck: MeTypes;
}
import { Resolver, Query } from "type-graphql";
import { MeNameSpaceTypes } from "./MeNamespace.types";
#Resolver()
export class MeResolver {
#Query(() => MeNameSpaceTypes)
async Me() {
const response = {
hello: "world",
meCheck:{}
};
return response;
}
}
Result of code
query {
Me{
hello
meCheck{
meHello
}
}
}
--RESULT--
{
"data": {
"Me": {
"hello": "world",
"meCheck": {
"meHello": null
}
}
}
}
I got a null instead a meHello resolver. Where am I wrong?
Namespaced mutations are against GraphQL spec as they are not guarranted to run sequentially - more info in this discussion in GitHub issue related to your problem:
https://github.com/MichalLytek/type-graphql/issues/64

GraphQL Schema and Resolvers organization return null [duplicate]

This question already has answers here:
Why does a GraphQL query return null?
(6 answers)
Closed 3 years ago.
i am toying with the Star Wars API using GraphQL. Using GraphQL Playground, i get null values for the response for the joint entities.
I believe the reason is because of the organization of my schema and resolver files. Below are my codes and the files they are stored in, anyone can help? The current setup only returns the name of the Star Wars character but doesn't return the array of films details under the person/character
Thanks a lot
GQL Playground
{
"data": {
"getPerson": {
"name": "Obi-Wan Kenobi",
"films": [
{
"title": null,
"director": null
}
]
}
}
}
graphql/schema.ts
import { gql } from "apollo-server-express";
export const typeDefs = gql`
type Person {
name: String
height: String
mass: String
homeworld: Planet
films: [Film]
vehicles: [Vehicle]
}
type Planet {
name: String
diameter: String
climate: String
terrain: String
population: String
films: [Film]
}
type Film {
title: String
episode_id: Int
director: String
producer: String
releaseDate: String
}
type Vehicle {
name: String
model: String
manufacturer: String
length: String
crew: String
passengers: String
pilots: [Person]
}
type Query {
getPerson(id: Int!): Person
}
schema {
query: Query
}
`;
graphql/resolvers/index.ts
import PersonResolvers from "./person-resolvers";
export const resolvers = {
Query: {
getPerson: PersonResolvers.getPerson
}
};
graphql/person-resolvers.ts
import fetch from "node-fetch";
export default {
getPerson: async (_: any, { id }: { id: string }) => {
try {
const res = await fetch(`https://swapi.co/api/people/${id}/`);
return res.json();
} catch (error) {
throw error;
}
},
Person: {
films: (person: any) => {
const promises = person.films.map(async (url: string) => {
const res = await fetch(url);
return res.json();
});
return Promise.all(promises);
},
vehicles: (person: any) => {
const promises = person.vehicles.map(async (url: string) => {
const res = await fetch(url);
return res.json();
});
return Promise.all(promises);
}
},
Vehicle: {
pilots: (vehicle: any) => {
const promises = vehicle.pilots.map(async (url: string) => {
const res = await fetch(url);
return res.json();
});
return Promise.all(promises);
}
}
};
I have managed to get it work with this folder organization
For those looking for answers, u can check out my repo below
myhendry gql github repo

Hello world example for Apollo Client 2 + React?

Im trying to return a string with React and GraphQL but I'm getting stuck at the first stage. Here is my attempt:
import { makeExecutableSchema } from 'graphql-tools';
const typeDefs = `
type Query {
author: Person
}
type Person {
name: String
}
`;
const resolvers = {
Query: {
author: { name: 'billy' },
},
};
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
createApolloServer({ schema });
And this is my understanding of that code:
In my schema I've defined a Query called author which should return a Person.
A Person has a name field which is a string.
My resolver has a Query called author which should return an object with a name field of value 'billy'
However in my Graphicool browser tools this query:
query {
author{
name
}
}
Returns this:
{
"data": {
"author": null
}
}
Resolvers are functions which GraphQL will call when resolving that particular field. That means your resolvers object should look more like this:
const resolvers = {
Query: {
author: () => ({ name: 'billy' }),
},
}
Or, alternatively,
const resolvers = {
Query: {
author() {
return { name: 'billy' }
},
},
}
You can check out the docs for more information.
import { createApolloServer } from 'meteor/apollo';
import { makeExecutableSchema } from 'graphql-tools';
import merge from 'lodash/merge'; // will be useful later when their are more schemas
import GroupsSchema from './Groups.graphql';
import GroupsResolvers from './resolvers';
const typeDefs = [GroupsSchema];
const resolvers = merge(GroupsResolvers);
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
createApolloServer({ schema });
In ./Groups.graphql:
type Query {
hi: String
groups: [Group]
group: Group
}
type Group {
name: String
}
In './resolvers':
export default {
Query: {
hi() {
return 'howdy';
},
groups() {
return [{ name: 'one', _id: '123' }, { name: 'two', _id: '456' }];
// return Groups.find().fetch();
},
group() {
return { name: 'found me' };
},
},
};
In a React component:
const mainQuery = gql`
{
groups {
name
}
}
`;
export default graphql(mainQuery)(ComponentName);

Resources