I have the following graphql schema:
type Post
#model {
id: ID!
title: String!
content: String!
comments: [Comment] #hasMany(indexName: "byPost", fields: ["id"])
}
type Comment
#model {
id: ID!
message: String
post: Post #belongsTo(fields: ["postID"])
postID: ID #index(name: "byPost")
}
AppSync generated the following query for this schema:
export const listPosts = /* GraphQL */ `
query ListPosts(
$filter: ModelPostFilterInput
$limit: Int
$nextToken: String
) {
listPosts(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
id
title
content
comments {
nextToken
}
createdAt
updatedAt
}
nextToken
}
}
`;
Now when I use it like this:
const postData = await API.graphql({
query: listPosts,
});
There are no comments in result, is returns comments: { nextToken: null } as part of a post, but there are comments, associated with the post in the database.
How can I get nested data in this case?
Related
I am using Next JS 13 and Sanity 3 GraphQL API to build a simple portfolio site. My problem is to get a single post/project by slug instead of id.
The id url ends up looking like:
http://127.0.0.1:3000/projects/093e9421-3dec-4b22-a106-63dd31b0e685
but I want it to use the slug instead.
This is the getStaticFunction function
export async function getStaticProps({ params }: any) {
const GET_PROJECTS = gql`
query SingleProject($slug: String) {
Project(slug: $slug) {
title
_id
slug {
current
}
bodyRaw
summary
category {
title
}
projectImage {
asset {
url
}
}
}
}
`;
const response = await client.query({
query: GET_PROJECTS,
variables: {
slug: params.slug.current,
},
});
const project = response.data?.Project;
return {
props: {
project,
},
};
}
but this gives me:
ApolloError: Unknown argument "where" on field "Project" of type "RootQuery".
Field "Project" argument "id" of type "ID!" is required, but it was not provided.
I also tried to query using the where like so:
query SingleProject($slug: String!) {
Project(where: { slug: { current: { eq: $slug } } }) {
title
}
}
but I get a Unkown arugment "where" on field "Project" of type "RootQuery"
On my Amplify App, I am use this model:
type Post
#model {
id: ID!
title: String!
level: Int!
categories: [Int!]
}
It's easy to filter post by level.
Example: Retrieve all posts that have level 3
I am using this code:
const response = await API.graphql({
query: listPosts,
variables: {
filter: {
level: {
eq: 3
}
}
}
});
My problem is with the categories parameter.
Example: How retrieve all posts that have category 2? How retrieve all posts that have category 3 and 5?
Can you help me?
Regards
I try to make mutation with appolo, but I don't know what's the problem.
Everything work in the playground.
const ADD_PURCHASE = gql`
mutation addPurchaseById($data: {uniqueId: String, items: [{price: Int, name: String, description: String, image: String}]}) {
addPurchaseById(data: $data) {
price
name
image
description
}
}
`;
const [addPurchaseById, {data, loading}] = useMutation(ADD_PURCHASE);
here, my cart is an array of object: name, price, description, image.
This is how I try to make the request:
const uniqueId = getUniqueId();
await addPurchaseById({
variables: {data: {uniqueId: uniqueId, items: cart}},
});
On my server part, I have this in my typeDefs :
input ItemMutation {
price: Float!
name: String!
image: String!
description: String!
}
input Purchase {
uniqueId: String!
items: [ItemMutation]!
}
type Mutation {
addPurchaseById(data: Purchase!): [Item]!
}
I want to create a query fragment that I can use to query regular WordPress posts and custom post types which share the same properties. Assume I have the following code using graphql aliases:
query getData($includeCategory: Boolean!) {
wp {
data1: customPostTypes(where: {categoryName: "Exammple 1"}, first: 3) {
nodes {
...dataFragment
}
}
data2: posts(first:3) {
nodes {
...dataFragment
}
}
data3: customPostTypes(where: {categoryName:"Example 2"}, first: 3) {
nodes {
...dataFragment
}
}
}
}
and a single query fragment that looks like:
fragment dataFragment on WP_CustomPostType {
title
uri
status
id
categories #include(if: $includeCategory) {
nodes {
name
}
}
}
Because I have to define the type of field that the fragment will be used on, it prevents me from being able to use it for all the post types that I want to. The above example will work for customPostTypes only and not posts as the field that needs to be defined for that is WP_Post
This is purely for cosmetics but it would be awesome to reuse just one fragment for post types/custom post types with the same properties.
Is there a way I can use one query fragment for all of my post types?
UPDATE
This question is similar, however when working with WPGraphQL and custom post types, using code like this:
exports.sourceNodes = ({ actions }) => {
const { createTypes } = actions
const typeDefs = `
interface PostType {
title: String
uri: String!
status: String!
id: ID!
}
type Work implements Node & PostType {
title: String
uri: String!
status: String!
id: ID!
}
type Post implements Node & PostType {
title: String
uri: String!
status: String!
id: ID!
}
`
createTypes(typeDefs)
}
produces the error: UNHANDLED REJECTION Schema must contain uniquely named types but contains multiple types named "WP_Work"
I have the following resolver settings:
#set($questions = [])
#foreach($item in ${ctx.args.questions})
#set($item.id = $util.dynamodb.toDynamoDBJson($util.autoId()))
$util.qr($questions.add($util.dynamodb.toMapValues($item)))
#end
{
"version" : "2018-05-29",
"operation" : "BatchPutItem",
"tables" : {
"QuestionTable": $utils.toJson($questions)
}
}
And the following GraphQL schema:
input CreateQuestionInput {
text: String
sectionId: ID!
}
input CreateScoreInput {
score: Int!
questionId: ID!
userId: ID!
}
input CreateSectionInput {
title: String
subSection: String
}
input DeleteQuestionInput {
id: ID!
}
input DeleteScoreInput {
id: ID!
}
input DeleteSectionInput {
id: ID!
}
type Mutation {
...
createQuestion(input: CreateQuestionInput!): Question
batchCreateQuestion(questions: [CreateQuestionInput]!): [Question]
}
type Query {
getSection(id: ID!): Section
listSections(filter: TableSectionFilterInput, limit: Int, nextToken: String): SectionConnection
getScore(id: ID!): Score
listScores(filter: TableScoreFilterInput, limit: Int, nextToken: String): ScoreConnection
getQuestion(id: ID!): Question
listQuestions(filter: TableQuestionFilterInput, limit: Int, nextToken: String): QuestionConnection
}
type Question {
id: ID!
text: String
sectionId: ID!
}
type QuestionConnection {
items: [Question]
nextToken: String
}
type Schema {
query: Query
}
type Score {
id: ID!
score: Int!
questionId: ID!
userId: ID!
}
type ScoreConnection {
items: [Score]
nextToken: String
}
type Section {
id: ID!
title: String
subSection: String
questions: [Question]
}
type SectionConnection {
items: [Section]
nextToken: String
}
input TableQuestionFilterInput {
id: TableIDFilterInput
text: TableStringFilterInput
sectionId: TableIDFilterInput
}
input UpdateQuestionInput {
id: ID!
text: String
sectionId: ID
}
(I've redacted some of the schema as it was fairly large).
When I attempt to run the query:
mutation BatchCreateQuestions($sec: ID!) {
batchCreateQuestion(questions: [
{
text: "Tester 1"
sectionId: $sec
},
{
text: "Tester 2",
sectionId: $sec
}
]) {
id
text
sectionId
}
}
With the variables:
{ "sec": "abc123" }
I get the response:
{
"data": {
"batchCreateQuestion": [
null,
null
]
}
}
And when I check the DynamoDB table, it hasn't saved the values. I've granted full dynamodb permissions for this datasource, but still no joy.
Turns out I'd given batch write permissions to a similarly named role instead of the role affecting this data source. If you see a similar issue, check your IAM roles/permissions. Silly me.
What does your response template look like in the resolver? It should be $util.toJson($ctx.result.data.QuestionTable) based on the above table name being QuestionTable as that gets automatically translated into the response context.