Why is the query empty in the graph ql? - graphql

Why the following query result is wrong and null returns
const Mutation = {
createJob: (root, { input}) => {
const id = db.jobs.create({ input });
return db.jobs.get(id);
},
};

Related

Multiple Sorting with Mongoose and MongoDB

For some reason, I can't sort with multiple parameters in Mongoose. One parameter works just fine, but the ones after that are not working.
My query looks like this : 127.0.0.1:3000/api/v1/tours?sort=ratingsAverage,price
exports.getAllTours = async (req, res) => {
const queryObj = { ...req.query };
let query = Tour.find(queryObj);
if (req.query.sort) {
const sortBy = req.query.sort.split(',').join(' ');
query = query.sort(sortBy);
}
const tours = await query;
res.status(200).json({
status: 'success',
requestedAt: req.requestTime,
results: tours.length,
data: {
tours
}
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err
});
}
};

fetch list of data got incomplete result, how to remove the limitation

i try to get all the data which is belong to logged user but got incomplete result, it suppose to be returning 22 data but the code only returning 19 data
export const getHistoryList = async (filterPayload: Array<IFilterPayload>, dispatch: Dispatch<any>) => {
dispatch(setProductStart())
let payload: IHistoryList[] = [];
let filter: ModelImportHistoryFilterInput = {};
let orFilter: ModelImportHistoryFilterInput[] = [];
filterPayload.map((item) => {
if (item.type === "merchantID") {
filter = { ...filter, merchantImportHistoriesId: { eq: item.value } };
}
if (item.type === "action") {
orFilter.push({ action: { eq: ImportHistoryAction[item.value as keyof typeof ImportHistoryAction] } });
}
});
orFilter = orFilter.filter(item => item.action?.eq !== undefined);
if (orFilter.length > 0) {
filter = { ...filter, or: orFilter };
}
const result = await (API.graphql({
query: queriesCustom.listImportHistoriesCustom,
variables: { filter: filter }
}) as Promise<{ data?: any }>)
.then((response) => {
const data = response.data.listImportHistories.items;
return data
})
...
}
if i remove the filter from variables i got only 100 data from total 118 data
i already try this temporary solution to set the limit in variables to 2000, which is worked, but i don't think this is the correct approach
const result = await (API.graphql({
query: queriesCustom.listImportHistoriesCustom,
variables: { limit: 2000, filter: filter }
}) as Promise<{ data?: any }>)
.then((response) => {
const data = response.data.listImportHistories.items;
return data
})
how can i overcome this problem please help?

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");
}

Access return data from resolver in graphql

I want to access the country field from my resolver. The country is being returned by query but since Product is a list I can only access the object inside items return by query. Is there any way I can have access to whole returned data from query or any way to pass it further down as an argument to my resolver function
//schema
type ProductCollectionPage {
items: [Product!]!
}
//resolver
const resolvers = {
Product: {
variants: async (obj: any, args: any, { dataSources }: any): Promise<IProductVariantPage> => {
const { id } = obj;
// want to access country here
return (dataSources.xyz as XyzRepository).retriveProducts(country, id);
}
},
Query: {
products: async (
obj: any,
{ id }: { id: string },
{ dataSources }: any
): Promise<
any
> => {
const locationDetails = await (dataSources.abc as InventoryLocationsRepository).retrieveInventoryLocation(id);
const country = locationDetails.country;
const response = await (dataSources.abc as XyzRepository).retriveProductIds(country);
// response.list === [{id: 1}, {id:2}]
return {
country,
items: response.list
}
}
}
};
As arrays are objects in javascript then you can just assign additional property to response.list:
response.list.country = country;

GraphQL: Field Resolver Not Firing on Subscription Query?

I've got a subscription query, MessageFolder_Subscription, that looks like this:
QUERY
const MESSAGEFOLDER_SUBSCRIPTION_QUERY = gql`
subscription ($localUserID: String!){
MessageFolder_Subscription(userID: $localUserID){
id
remoteUserData{
id
name_title
name_first
name_last
[...more fields...]
}
},
}
`;
Here's the schema for it:
SCHEMA
type myUserData {
id: String
gender: String
name_title: String
name_first: String
*[...more fields...]*
}
type messageFolder{
id: String
remoteUserData: myUserData
}
type Subscription {
MessageFolder_Subscription(userID: String!): messageFolder
}
Here's how I'm doing the resolvers:
RESOLVERS
const resolvers = {
//FIELD RESOLVER
MessageFolder_Subscription: {
subscribe: withFilter(
() => pubsub.asyncIterator(MSGFOLDER_ADDED_CHANNEL),
(payload, args) => {
debugger; <=== NEVER FIRES
if (typeof (payload) === 'undefined') {
return false;
}
let result = false;
const userId = Meteor.userId();
// let messageFolder = MessageFolder_Subscription.messageFolder;
result = (userId === args.fromID || args === MSGFOLDERargs.toID);
return result;
}
)
},
//ROOT RESOLVER
*[......more resolvers here.....]*
Subscription: {
MessageFolder_Subscription: {
subscribe: withFilter(
() => pubsub.asyncIterator(MSGFOLDER_ADDED_CHANNEL),
(payload, args) => {
debugger;
if (typeof (payload) === 'undefined') {
return false;
}
let result = false;
const userId = Meteor.userId();
// let messageFolder = MessageFolder_Subscription.messageFolder;
result = (userId === args.fromID || args === MSGFOLDERargs.toID);
return result;
}
)
}
}
When I mutate a related item, the MessageFolder_Subscription query is fired by pubsub as expected. Tracing through, I can see that it returns true.
But for some reason, the field resolver, for the field remoteUserData on MessageFolder_Subscription, never fires.
What am I missing?
Solved. I had to add the __typename: field:
const messageFolder_Subscription = {
__typename: 'messageFolder_Subscription',
id: userID,
}
...to the MessageFolder_Subscription subscription object, when it was created in the mutation resolver, prior to being passed to pubsub.

Resources