I am scraping a Hotel Website that uses GraphQL. I have a query that gets all hotels and another query that gets the offers of the hotel. So i have to run the second query for all hotels. If i insert the second query into the first query. It says its not allowed to use with that object. Is there a way to run a function inside of an object even though it is not related to that object or is there another way to achieve this?
I cant introspect the scheme because its disabled. So its hard to find the variable name of the offers inside of the Property object, if it even exists.
Can I maybe combine all queries of the second query into 1 huge query containing all the hotels?
query 1:
query LodgingPwaPropertySearch(
$context: ContextInput!,
$destination: DestinationInput!,
$rooms: [RoomInput!],
$dateRange: PropertyDateRangeInput,
$sort: PropertySort,
$filters: PropertySearchFiltersInput,
$marketing: PropertyMarketingInfoInput,
$legacyCriteria: LegacyPropertySearchCriteriaInput,
$propertyShopOptions: PropertyShopOptionsInput,
$searchPagination: PaginationInput,
$searchIntent: SearchIntentInput,
$shoppingContext: ShoppingContextInput,
$criteria: PropertySearchCriteriaInput,
$returnPropertyType: Boolean = true
) {
propertySearch(
context: $context
destination: $destination
rooms: $rooms
dateRange: $dateRange
sort: $sort
filters: $filters
marketing: $marketing
legacyCriteria: $legacyCriteria
propertyShopOptions: $propertyShopOptions
searchPagination: $searchPagination
searchIntent: $searchIntent
shoppingContext: $shoppingContext
criteria: $criteria
returnPropertyType: $returnPropertyType
) {
propertySearchListings {
... on Property {
...PropertyFields
}
}
summary {
pricedHotelSize
region {
name
id
}
matchedPropertiesSize
resultsHeading
}
}
}
fragment PropertyFields on Property {
__typename
...CommonPropertyCardFields
availability {
available
}
offerSummary {
messages {
message
theme
type
mark {
id
url {
value
}
}
}
}
mapMarker {
type
latLong {
latitude
longitude
}
}
neighborhood {
name
}
}
fragment CommonPropertyCardFields on Property {
id
name
price {
displayMessages {
lineItems {
...EnrichedMessageFragment
}
}
lead {
formatted
}
}
reviews {
scoreDenominator
score
localizedScore
total
localizedTotal
}
propertyDetailsLink {
uri {
value
}
}
}
fragment EnrichedMessageFragment on LodgingEnrichedMessage {
__typename
value
state
}
query 2 (shorten):
query PropertyOffersQuery(
$context: ContextInput!,
$propertyId: String!,
$searchCriteria: PropertySearchCriteriaInput,
$shoppingContext: ShoppingContextInput,
$travelAdTrackingInfo: PropertyTravelAdTrackingInfoInput,
$searchOffer: SearchOfferInput,
$referrer: String
) {
propertyOffers(
context: $context
propertyId: $propertyId
referrer: $referrer
searchCriteria: $searchCriteria
searchOffer: $searchOffer
shoppingContext: $shoppingContext
travelAdTrackingInfo: $travelAdTrackingInfo
) {
id
__typename
...PropertyOffersFragment
...PropertyUnitListViewFragment
}
}
fragment PropertyOffersFragment on OfferDetails {
...ListingsFragment
__typename
}
fragment ListingsFragment on OfferDetails {
categorizedListings {
...PropertyUnitCategorizationFragment
...VerticalMessagingCardFragment
...LodgingHeaderFragment
__typename
}
__typename
}
fragment PropertyUnitCategorizationFragment on LodgingCategorizedUnit {
__typename
header {
text
}
features {
...PropertyFeaturesFragment
__typename
}
...UnitCategorizationFragment
}
fragment MessageResultFragment on MessageResult {
title {
text
...MessagingResultTitleMediaFragment
__typename
}
subtitle {
text
...MessagingResultTitleMediaFragment
__typename
}
action {
primary {
...MessageActionContent
__typename
}
secondary {
...MessageActionContent
__typename
}
__typename
}
__typename
}
fragment MessageActionContent on MessagingAction {
text
linkUrl
referrerId
actionDetails {
action
accessibilityLabel
__typename
}
analytics {
linkName
referrerId
__typename
}
__typename
}
fragment MessagingResultTitleMediaFragment on MessagingResultTitle {
icon {
id
description
size
__typename
}
illustration {
assetUri {
value
__typename
}
description
__typename
}
mark {
id
__typename
}
egdsMark {
id
__typename
}
__typename
}
fragment LodgingEnrichedMessageFragment on LodgingEnrichedMessage {
__typename
subText
value
theme
state
accessibilityLabel
icon {
id
size
__typename
}
mark {
id
__typename
}
egdsMark {
url {
value
__typename
}
__typename
}
}
fragment LodgingPriceSummaryFragment on Offer {
price {
options {
leadingCaption
displayPrice {
formatted
__typename
}
disclaimer {
value
__typename
}
priceDisclaimer {
content
primaryButton {
text
__typename
}
trigger {
icon {
description
__typename
}
__typename
}
__typename
}
accessibilityLabel
strikeOut {
formatted
__typename
}
loyaltyPrice {
unit
amount {
formatted
__typename
}
totalStrikeOutPoints {
formatted
__typename
}
__typename
}
__typename
}
priceMessaging {
value
theme
__typename
}
__typename
}
__typename
}
fragment PropertyRatePlanBadgeFragment on RatePlan {
badge {
theme_temp
text
icon_temp {
id
description
size
title
__typename
}
__typename
}
__typename
}
fragment PropertyOffersPriceChangeMessageFragment on RatePlan {
headerMessage {
...LodgingEnrichedMessageFragment
__typename
}
__typename
}
fragment PriceSummaryFragment on PropertyPrice {
displayMessages {
lineItems {
...PriceMessageFragment
...EnrichedMessageFragment
__typename
}
__typename
}
options {
leadingCaption
displayPrice {
formatted
__typename
}
disclaimer {
value
__typename
}
priceDisclaimer {
content
primaryButton {
text
__typename
}
trigger {
icon {
description
__typename
}
__typename
}
__typename
}
accessibilityLabel
strikeOut {
formatted
__typename
}
loyaltyPrice {
unit
amount {
formatted
__typename
}
totalStrikeOutPoints {
formatted
__typename
}
__typename
}
__typename
}
priceMessaging {
value
theme
__typename
}
__typename
}
fragment PriceMessageFragment on DisplayPrice {
__typename
role
price {
formatted
accessibilityLabel
__typename
}
disclaimer {
content
primaryUIButton {
accessibility
primary
__typename
}
__typename
}
}
fragment EnrichedMessageFragment on LodgingEnrichedMessage {
__typename
value
state
}
fragment HighlightedMessagesFragment on RatePlan {
id
highlightedMessages {
...LodgingPlainDialogFragment
...LodgingEnrichedMessageFragment
...LodgingPlainMessageFragment
__typename
}
__typename
}
fragment LodgingPlainDialogFragment on LodgingPlainDialog {
content
primaryUIButton {
...UIPrimaryButtonFragment
__typename
}
secondaryUIButton {
...UISecondaryButtonFragment
__typename
}
primaryButton {
text
analytics {
linkName
referrerId
__typename
}
__typename
}
trigger {
clientSideAnalytics {
linkName
referrerId
__typename
}
icon {
description
id
__typename
}
theme
value
secondaryValue
__typename
}
__typename
}
fragment UIPrimaryButtonFragment on UIPrimaryButton {
primary
action {
__typename
analytics {
referrerId
linkName
__typename
}
... on UILinkAction {
resource {
value
__typename
}
__typename
}
}
__typename
}
fragment UISecondaryButtonFragment on UISecondaryButton {
primary
action {
__typename
analytics {
referrerId
linkName
__typename
}
... on UILinkAction {
resource {
value
__typename
}
__typename
}
}
__typename
}
fragment LodgingPlainMessageFragment on LodgingPlainMessage {
value
__typename
}
fragment AvailabilityCallToActionFragment on AvailabilityCallToAction {
__typename
... on LodgingPlainMessage {
__typename
value
}
... on LodgingButton {
__typename
text
}
}
fragment MarketingSectionFragment on MarketingSection {
title {
text
__typename
}
feeDialog {
title
content
tertiaryUIButton {
primary
__typename
}
trigger {
value
mark {
id
__typename
}
icon {
id
size
__typename
}
clientSideAnalytics {
linkName
referrerId
__typename
}
__typename
}
__typename
}
paymentDetails {
...LodgingEnrichedMessageFragment
__typename
}
__typename
}
fragment PropertyReserveButtonFragment on RatePlan {
id
reserveCallToAction {
__typename
... on EtpDialog {
trigger {
value
accessibilityLabel
__typename
}
toolbar {
icon {
description
__typename
}
title
__typename
}
__typename
}
... on LodgingForm {
...PropertyLodgingFormButtonFragment
__typename
}
}
etpDialogTopMessage {
...MessageResultFragment
__typename
}
priceDetails {
action {
... on SelectPackageActionInput {
packageOfferId
__typename
}
__typename
}
price {
multiItemPriceToken
__typename
}
hotelCollect
propertyNaturalKeys {
id
checkIn {
month
day
year
__typename
}
checkOut {
month
day
year
__typename
}
inventoryType
noCreditCard
ratePlanId
roomTypeId
ratePlanType
rooms {
childAges
numberOfAdults
__typename
}
shoppingPath
__typename
}
noCreditCard
paymentModel
...PropertyPaymentOptionsFragment
__typename
}
__typename
}
fragment PropertyLodgingFormButtonFragment on LodgingForm {
action
inputs {
... on LodgingTextInput {
name
type
value
__typename
}
__typename
}
method
submit {
text
accessibilityLabel
analytics {
linkName
referrerId
__typename
}
lodgingClientSideAnalyticsSuccess {
campaignId
events {
banditDisplayed
eventTarget
eventType
payloadId
__typename
}
__typename
}
__typename
}
__typename
}
fragment PropertyPaymentOptionsFragment on Offer {
etpModalPolicies
loyaltyMessage {
... on LodgingEnrichedMessage {
value
state
__typename
}
__typename
}
offerBookButton {
...PropertyLodgingFormButtonFragment
__typename
}
...PropertyPaymentPriceFragment
price {
...PriceSummaryFragment
__typename
}
__typename
}
fragment PropertyPaymentPriceFragment on Offer {
price {
lead {
formatted
__typename
}
priceMessaging {
value
theme
__typename
}
__typename
}
__typename
}
fragment PricePresentationDialogFragment on Offer {
pricePresentationDialog {
toolbar {
title
icon {
description
__typename
}
clientSideAnalytics {
linkName
referrerId
__typename
}
__typename
}
trigger {
clientSideAnalytics {
linkName
referrerId
__typename
}
value
__typename
}
__typename
}
pricePresentation {
title {
primary
__typename
}
sections {
...PricePresentationSectionFragment
__typename
}
footer {
header
messages {
...PriceLineElementFragment
__typename
}
__typename
}
__typename
}
__typename
}
fragment PricePresentationSectionFragment on PricePresentationSection {
header {
name {
...PricePresentationLineItemEntryFragment
__typename
}
enrichedValue {
...PricePresentationLineItemEntryFragment
__typename
}
__typename
}
subSections {
...PricePresentationSubSectionFragment
__typename
}
__typename
}
fragment PricePresentationSubSectionFragment on PricePresentationSubSection {
header {
name {
primaryMessage {
__typename
... on PriceLineText {
primary
__typename
}
... on PriceLineHeading {
primary
__typename
}
}
__typename
}
enrichedValue {
...PricePresentationLineItemEntryFragment
__typename
}
__typename
}
items {
...PricePresentationLineItemFragment
__typename
}
__typename
}
fragment PricePresentationLineItemFragment on PricePresentationLineItem {
enrichedValue {
...PricePresentationLineItemEntryFragment
__typename
}
name {
...PricePresentationLineItemEntryFragment
__typename
}
__typename
}
fragment PricePresentationLineItemEntryFragment on PricePresentationLineItemEntry {
primaryMessage {
...PriceLineElementFragment
__typename
}
secondaryMessages {
...PriceLineElementFragment
__typename
}
__typename
}
fragment PriceLineElementFragment on PricePresentationLineItemMessage {
__typename
...PriceLineTextFragment
...PriceLineHeadingFragment
...InlinePriceLineTextFragment
}
fragment PriceLineTextFragment on PriceLineText {
__typename
theme
primary
weight
additionalInfo {
...AdditionalInformationPopoverFragment
__typename
}
icon {
id
description
size
__typename
}
}
fragment AdditionalInformationPopoverFragment on AdditionalInformationPopover {
icon {
id
description
size
__typename
}
enrichedSecondaries {
...AdditionalInformationPopoverSectionFragment
__typename
}
analytics {
linkName
referrerId
__typename
}
__typename
}
fragment AdditionalInformationPopoverSectionFragment on AdditionalInformationPopoverSection {
__typename
... on AdditionalInformationPopoverTextSection {
...AdditionalInformationPopoverTextSectionFragment
__typename
}
... on AdditionalInformationPopoverListSection {
...AdditionalInformationPopoverListSectionFragment
__typename
}
... on AdditionalInformationPopoverGridSection {
...AdditionalInformationPopoverGridSectionFragment
__typename
}
}
fragment AdditionalInformationPopoverTextSectionFragment on AdditionalInformationPopoverTextSection {
__typename
text {
text
__typename
}
}
fragment AdditionalInformationPopoverListSectionFragment on AdditionalInformationPopoverListSection {
__typename
content {
__typename
items {
text
__typename
}
}
}
fragment AdditionalInformationPopoverGridSectionFragment on AdditionalInformationPopoverGridSection {
__typename
subSections {
header {
name {
primaryMessage {
...AdditionalInformationPopoverGridLineItemMessageFragment
__typename
}
__typename
}
__typename
}
items {
name {
...AdditionalInformationPopoverGridLineItemEntryFragment
__typename
}
enrichedValue {
...AdditionalInformationPopoverGridLineItemEntryFragment
__typename
}
__typename
}
__typename
}
}
fragment AdditionalInformationPopoverGridLineItemEntryFragment on PricePresentationLineItemEntry {
primaryMessage {
...AdditionalInformationPopoverGridLineItemMessageFragment
__typename
}
secondaryMessages {
...AdditionalInformationPopoverGridLineItemMessageFragment
__typename
}
__typename
}
fragment AdditionalInformationPopoverGridLineItemMessageFragment on PricePresentationLineItemMessage {
... on PriceLineText {
__typename
primary
}
... on PriceLineHeading {
__typename
tag
size
primary
}
__typename
}
fragment PriceLineHeadingFragment on PriceLineHeading {
__typename
primary
tag
size
additionalInfo {
...AdditionalInformationPopoverFragment
__typename
}
icon {
id
description
size
__typename
}
}
fragment InlinePriceLineTextFragment on InlinePriceLineText {
__typename
inlineItems {
...PriceLineTextFragment
__typename
}
}
fragment PropertyFeaturesFragment on PropertyInfoItem {
text
graphic {
__typename
... on Icon {
id
__typename
}
... on Mark {
description
id
__typename
}
}
__typename
}
fragment LodgingPlainFullscreenDialogFragment on LodgingPlainDialog {
__typename
content
trigger {
clientSideAnalytics {
linkName
referrerId
__typename
}
icon {
description
id
__typename
}
theme
value
__typename
}
toolbar {
title
icon {
description
__typename
}
clientSideAnalytics {
linkName
referrerId
__typename
}
__typename
}
}
fragment PropertyOffersRateViewScarcityFragment on Offer {
availability {
scarcityMessage
__typename
}
__typename
}
fragment PropertyOffersDetailsDialogFragment on PropertyUnitDetailsDialog {
toolbar {
title
icon {
description
__typename
}
__typename
}
content {
ratePlanTitle {
text
__typename
}
dialogFeatures {
listItems {
text
icon {
id
description
__typename
}
__typename
}
__typename
}
details {
header {
text
subText
__typename
}
contents {
heading
items {
text
__typename
}
__typename
}
__typename
}
__typename
}
__typename
}
fragment RatePlanWithAmenitiesFragment on RatePlan {
shareUrl {
accessibilityLabel
value
link {
clientSideAnalytics {
linkName
referrerId
__typename
}
uri {
relativePath
value
__typename
}
__typename
}
__typename
}
id
name
description
amenities {
...RatePlanAmenitiesFragment
__typename
}
...PropertyRatePlanBadgeFragment
paymentPolicy {
paymentType
heading
price {
...PriceSummaryFragment
__typename
}
descriptions {
heading
items {
text
__typename
}
__typename
}
__typename
}
priceDetails {
optionTitle {
text
__typename
}
pointsApplied
...PropertyOffersRateViewScarcityFragment
...LodgingPriceSummaryFragment
...PriceBreakdownSummaryFragment
...PricePresentationDialogFragment
price {
...PriceSummaryFragment
__typename
}
__typename
}
marketingSection {
...MarketingSectionFragment
__typename
}
...HighlightedMessagesFragment
...PropertyOffersPriceChangeMessageFragment
...PropertyReserveButtonFragment
loyaltyMessage {
...LodgingEnrichedMessageFragment
__typename
}
__typename
}
fragment PriceBreakdownSummaryFragment on Offer {
priceBreakDownSummary {
priceSummaryHeading {
...LodgingEnrichedMessageFragment
__typename
}
sections {
...PriceSummarySectionFragment
__typename
}
disclaimers {
...LodgingEnrichedMessageFragment
__typename
}
__typename
}
__typename
}
fragment PriceSummarySectionFragment on PriceSummarySection {
sectionHeading {
...LodgingEnrichedMessageFragment
__typename
}
sectionFooter {
...PriceSummaryFooterFragment
__typename
}
items {
...PriceSummaryLineItemFragment
__typename
}
__typename
}
fragment PriceSummaryLineItemFragment on PriceSummaryLineItem {
name {
primaryMessage {
...LodgingEnrichedMessageFragment
__typename
}
secondaryMessages {
...LodgingEnrichedMessageFragment
__typename
}
__typename
}
value {
primaryMessage {
...LodgingEnrichedMessageFragment
__typename
}
secondaryMessages {
...LodgingEnrichedMessageFragment
__typename
}
__typename
}
__typename
}
fragment PriceSummaryFooterFragment on PriceSummaryFooter {
footerMessages {
...LodgingEnrichedMessageFragment
__typename
}
__typename
}
fragment RatePlanAmenitiesFragment on RatePlanAmenity {
icon {
id
description
size
__typename
}
description
additionalInformation
__typename
}
fragment LinkTriggerFragment on LodgingDialogTriggerMessage {
value
accessibilityLabel
__typename
}
fragment AvailabilityCtaFragment on PropertyUnit {
availabilityCallToAction {
...AvailabilityCallToActionFragment
__typename
}
__typename
}
fragment SpaceDetailsHeaderFragment on SpaceDetails {
header {
text
__typename
}
summary
__typename
}
fragment SpaceDetailsSpacesFragment on SpaceDetails {
spaces {
name
description
icons {
description
id
size
__typename
}
__typename
}
__typename
}
fragment SpaceDetailsFloorPlanFragment on SpaceDetails {
floorPlan {
images {
alt
image {
description
url
__typename
}
subjectId
__typename
}
toolbar {
icon {
description
id
size
__typename
}
title
__typename
}
trigger {
value
__typename
}
__typename
}
__typename
}
fragment RoomAmenitiesDescriptionFragment on PropertyContentSection {
header {
text
__typename
}
bodySubSections {
contents {
...RoomAmenityContentFragment
__typename
}
__typename
}
__typename
}
fragment RoomAmenityContentFragment on PropertyContent {
header {
text
icon {
id
__typename
}
__typename
}
items {
... on PropertyContentItemMarkup {
...RoomAmenityContentTextFragment
__typename
}
__typename
}
__typename
}
fragment RoomAmenityContentTextFragment on PropertyContentItemMarkup {
content {
text
__typename
}
__typename
}
fragment SpaceDetailsFragment on SpaceDetails {
...SpaceDetailsHeaderFragment
...SpaceDetailsSpacesFragment
...SpaceDetailsFloorPlanFragment
__typename
}
fragment UnitCategorizationFragment on LodgingCategorizedUnit {
primarySelections {
propertyUnit {
...UnitCategorizationPropertyUnitFragment
__typename
}
primarySelection {
...UnitCategorizationSelectionFragment
__typename
}
secondarySelections {
recommendedSelection
secondarySelection {
...UnitCategorizationSelectionFragment
__typename
}
tertiarySelections {
...UnitCategorizationSelectionFragment
dialog {
...LodgingPlainFullscreenDialogFragment
__typename
}
__typename
}
__typename
}
__typename
}
primaryHeader {
...SelectionHeaderFragment
__typename
}
secondaryHeader {
...SelectionHeaderFragment
__typename
}
tertiaryHeader {
...SelectionHeaderFragment
__typename
}
__typename
}
fragment SelectionHeaderFragment on LodgingOfferSelectionHeader {
title {
text
subText
__typename
}
...UnitCategorizationComplexDialogFragment
__typename
}
fragment UnitCategorizationComplexDialogFragment on LodgingOfferSelectionHeader {
dialog {
content {
content
title {
text
__typename
}
__typename
}
primaryUIButton {
...UIPrimaryButtonFragment
__typename
}
toolbar {
title
icon {
description
__typename
}
clientSideAnalytics {
linkName
referrerId
__typename
}
__typename
}
trigger {
clientSideAnalytics {
linkName
referrerId
__typename
}
icon {
id
description
__typename
}
value
__typename
}
__typename
}
__typename
}
fragment UnitCategorizationPropertyUnitFragment on PropertyUnit {
...AvailabilityCtaFragment
detailsDialog {
...PropertyOffersDetailsDialogFragment
toolbar {
clientSideAnalytics {
referrerId
linkName
__typename
}
__typename
}
trigger {
...LinkTriggerFragment
clientSideAnalytics {
referrerId
linkName
__typename
}
__typename
}
__typename
}
id
ratePlans {
...RatePlanWithAmenitiesFragment
...UnitCategorizationRatePlanFragment
__typename
}
roomAmenities {
...RoomAmenitiesDescriptionFragment
__typename
}
unitGallery {
accessibilityLabel
images {
image {
description
url
__typename
}
__typename
}
__typename
}
spaceDetails {
...SpaceDetailsFragment
__typename
}
__typename
}
Related
What is the reason for getting null in subscription response, getting proper value in mutation response
subscription MySubscription {
updateFieldResponseSubscription(id: 1){
__typename
... on TaskFieldResponse {
id
fieldId
field {
response {
... on GQLStringType {
stringVal: value
__typename
}
__typename
}
__typename
}
__typename
}
}
}
Here I am getting null for the stringVal
My Mutation is
mutation MyMutation($inputArguments: UpdateFieldResponseArgs!) {
updateFieldResponse(inputArguments: $inputArguments){
__typename
... on TaskFieldResponse {
id
fieldId
field {
response {
... on GQLStringType {
stringVal: value
__typename
}
__typename
}
__typename
}
__typename
}
}
}
I need to know with my GraphQL query request when one of the product variants doesn't have the relative image.
I have tried to figure it out how to do that but when there is no variant image the image url fallback to the default product image. (Image associated with the product variant. This field falls back to the product image if no image is available.).
https://shopify.dev/api/storefront/2022-04/objects/ProductVariant#fields
query ($productHandle: String!) {
product(handle: $productHandle) {
title
vendor
description
handle
availableForSale
images(first: 50) {
edges {
node {
id
url(transform: { maxWidth: 1100 })
}
}
}
priceRange {
maxVariantPrice {
amount
}
}
variants(first: 100) {
edges {
node {
compareAtPriceV2 {
amount
}
title
id
sku
quantityAvailable
image {
id
url // this url fallback to the default url when there is no image
ico: url(transform: { maxWidth: 100 })
__typename
altText
}
}
}
}
}
}
I have the following graphql code in my strapi and nextjs project. The code is working in the graphql end point playground but some how it keeps getting error in my local environment showing message: 'Syntax Error: Expected Name, found <EOF>.', when I try to fetch data from nextjs. I have ready this strapi documentation but cant seems to find anything relevant with my current issues. Any can please tell me what error I am making here?
export async function getPostAndMorePosts(slug, preview) {
const data = await fetchAPI(
`
fragment FileParts on UploadFileEntityResponse {
data {
id
attributes {
alternativeText
width
height
mime
url
formats
}
}
}
query Posts($slug: String!) {
posts(filters: {slug: {eq: $slug}}) {
data{
attributes{
title
content
excerpt
slug
category{
data{
attributes{
name
}
}
}
coverImage{
...FileParts
}
}
}
}
morePost: posts(filters: {slug: {ne: $slug}},pagination: { start: 0, limit: 4 }) {
data{
attributes{
title
content
excerpt
slug
category{
data{
attributes{
name
}
}
}
coverImage{
...FileParts
}
publishedAt
}
}
}
}`,
{variables:{
slug:slug
}
}
)
return data
}
Your code needs a closing bracket which is misaligned at the moment! Look at the code below
export async function getPostAndMorePosts(slug, preview) {
const data = await fetchAPI(
`
fragment FileParts on UploadFileEntityResponse {
data {
id
attributes {
alternativeText
width
height
mime
url
formats
}
}
}
} -> closed here
query Posts($slug: String!) {
posts(filters: {slug: {eq: $slug}}) {
data{
attributes{
title
content
excerpt
slug
category{
data{
attributes{
name
}
}
}
coverImage{
...FileParts
}
}
}
}
morePost: posts(filters: {slug: {ne: $slug}},pagination: { start: 0, limit: 4 }) {
data{
attributes{
title
content
excerpt
slug
category{
data{
attributes{
name
}
}
}
coverImage{
...FileParts
}
publishedAt
}
}
}
`, -> removed from here
{variables:{
slug:slug
}
}
)
return data
}
So it's just an issue of {} alligment.
I am trying to search for a string across multiple fields with GraphQL.
I was able to use filter function with an or field, but it was not retrieving anything.
I want to be able to retrieve an array with all the items that contain the searched string in title or/and body ==> so if the query string was found in title or body retrieve it to array.
My code is:
const search_reviews= gql`
query SearchReviews ($my_query: String) {
reviews (filters: {title: {contains: $my_query}, or: {body: {contains: $my_query}} }) {
data{
id
attributes{
title
rating
body
categories{
data{
id
attributes
{
name
}
}
}
}
}
}
}
`
Works ok with only one field, but I want to have it in both fields
const search_reviews= gql`
query SearchReviews ($my_query: String!) {
reviews (filters: {body: {contains: $my_query} }) {
data{
id
attributes{
title
rating
body
categories{
data{
id
attributes
{
name
}
}
}
}
}
}
}
`
Seems that they changed the API.
Here is some code:
const search_reviews = gql`
query SearchReviews ($my_query: String!) {
reviews (filters: {or: [{body: {contains: $my_query} }, {title: {contains: $my_query}}]}) {
data{
id
attributes{
title
rating
body
categories{
data{
id
attributes
{
name
}
}
}
}
}
}
}
`
Basically you need to use $filters with an or to search in body or in the tile.
reviews (filters: {or: [{body: {contains: $my_query} }, {title: {contains: $my_query}}]})
Cheers to all!
I would like to create dynamic pages when I click a tag in an article or elsewhere on my website.
I'm using Next.js, SSG, and fetching the articles containing the tags from Contentful with the following GraphQL queries:
export async function getArticles() {
const articlesQuery = gql`
{
articleCollection(order: date_DESC) {
items {
title
slug
excerpt
date
contentfulMetadata {
tags {
name
id
}
}
featuredImage {
title
url
width
height
}
author {
name
photo {
fileName
url
width
height
}
title
twitterProfile
linkedInProfile
slug
}
}
}
}
`;
return graphQLClient.request(articlesQuery);
}
export async function getArticle(slug) {
const articleQuery = gql`
query getArticle($slug: String!) {
articleCollection(limit: 1, where: { slug: $slug }) {
items {
title
slug
excerpt
date
contentfulMetadata {
tags {
name
id
}
}
featuredImage {
title
url
width
height
}
author {
name
photo {
fileName
url
width
height
}
title
twitterProfile
linkedInProfile
slug
}
content {
json
links {
entries {
block {
sys {
id
}
__typename
... on VideoEmbed {
title
embedUrl
}
... on CodeBlock {
description
language
code
}
}
}
assets {
block {
sys {
id
}
url
title
width
height
}
}
}
}
}
}
}
`;
return graphQLClient.request(articleQuery, {
slug,
});
}
The contentfulMetadata is where the tags come from:
contentfulMetadata {
tags {
name
id
}
}
This is my [id].jsx file:
import { getArticles, getArticle } from "#utils/contentful";
export async function getStaticPaths() {
const data = await getArticles();
return {
paths: data.articleCollection.items.map((article) => ({
params: { id: article.contentfulMetadata.tags[0].id },
})),
fallback: false,
};
}
export async function getStaticProps(context) {
const data = await getArticle(context.params.id);
return {
props: { article: data.articleCollection.items[0] },
};
}
export default function TagPage({ article }) {
return (
<div>
<h1>{article.contentfulMetadata.tags.id}</h1>
</div>
);
}
I get the following error:
Error: Error serializing `.article` returned from `getStaticProps` in "/tags/[id]". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
When console.log(data.articleCollection.items.contentfulMetadata.tags.id); or console.log(data.articleCollection.items.contentfulMetadata.tags[0].id); within getStaticPaths function it provides the following error:
TypeError: Cannot read property 'tags' of undefined
Can anyone show how to create a dynamic page ([id].jsx) file, which shows the tag id as the header <h1> as well as all articles containing the same tag?
Contentful DevRel here 👋🏼.
article.contentfulMetadata.tags is an array, as an entry can have more than one tag. So you'll need to access the tag you want via article.contentfulMetadata.tags[0].id or article.contentfulMetadata.tags[desired_index].id and so on.
Here's an example GraphQL query:
query {
blogPostCollection {
items {
contentfulMetadata {
tags {
id
name
}
}
}
}
}
And here's the response with tags as an array:
"data": {
"blogPostCollection": {
"items": [
{
"contentfulMetadata": {
"tags": [
{
"id": "salmastag",
"name": "Salma s tag"
}
]
}
},
{
"contentfulMetadata": {
"tags": []
}
}
]
}
}
}
Notice how if a blog post doesn't have any PUBLIC tags assigned (the second entry in the response), an empty array is returned — you might want to do some safety checking in your code for this.