Problem with getting RAW format of excerpt in WPGraphQL using Apollo - javascript

When I try to get an excerpt from WPGraphQL plugin and pass excerpt(format: RAW) in the query, it's working fine in the WPGraphiQL window, but when I'm executing the same query in Vue Apollo it's always returning null.
Here is my code:
apollo: {
posts: gql`
query {
posts {
nodes {
title
uri
date
databaseId
featuredImage {
sourceUrl
}
excerpt(format: RAW)
}
}
}
`
},
Am I guessing right that it has to deal with enum type on the server-side and the way it's passed in Apollo query string? Also when I pass only excerpt without argument it returns excerpt with HTML tags, so... what's wrong?

Use excerpt(format: FORMATTED)
and use in html like this:
dangerouslySetInnerHTML={{ __html: node.excerpt }}

You can only access content in the RAW format if your user is authenticated. This is why you can see the RAW content in the WPGraphiQL window, but not when you try to get this same data from your Vue app. You need to authenticate the query in your app. https://www.wpgraphql.com/docs/authentication-and-authorization/

Related

GitHub GraphQL API query for response simplification [duplicate]

Let's say I've got a GraphQL query that looks like this:
query {
Todo {
label
is_completed
id
}
}
But the client that consumes the data from this query needs a data structure that's a bit different- e.g. a TypeScript interface like:
interface Todo {
title: string // "title" is just a different name for "label"
data: {
is_completed: boolean
id: number
}
}
It's easy enough to just use an alias to return label as title. But is there any way to make it return both is_completed and id under an alias called data?
There is no way to do that. Either change the schema to reflect the client's needs or transform the response after it is fetched on the client side.

How to convert a JS react page into an HTML page

So I'm working on a CMS project that allows users to create their own websites just like wordpress or other CMS platforms...
The users can implement different modals into their websites (text modal, image modal, search modal and other stuff), and then we create an object with the created page infos.
The Object contains all the page infos like the example bellow:
{
pageName: "Home page",
pageLink: "home",
pageSlug: "home-page",
pageMetaDescription: "home meta description",
pageMetaTitle : "home meta title",
pageModals : [
modal1: {
//modal infos here.
}
modal2: {
//modal infos here.
}
]
}
What I'm doing now is stocking these Objects on a database and when the user requests a page, I fetch the object and then generate a react JS file. But this approach isn't the best for performance or SEO.
So I would like to actually generate an HTML file from these Objects and store them in the database and when the user requests a page, it just loads the generated HTML file instead of fetching the Object and populating a react JS page.
If you have an Idea or approach to do this, I would like your help.
Yes you can use Next.js to handle your case
Next allow you to fetch some external data and render html based on api result
Here an example from documentation adapted for your cases
// pagesInfos will be populated at build time by getStaticProps()
function Blog({ pagesInfos }) {
const { pageSlug, pageMetaDescription , pageMetaTitle ...} = pagesInfos
return (
<div>
<h1>{postMetaTitle}</h1>
<p>{pageMetaDescription}</p>
</div>
)
}
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
const res = await fetch('https://.../getPages')
const pagesInfos = await res.json()
// By returning { props: { pagesInfos } }, the Blog component
// will receive `pagesInfos` as a prop at build time
return {
props: {
pagesInfos,
},
}
}
export default Blog
Here is full docs : https://nextjs.org/docs/basic-features/data-fetching/get-static-props

Strapi query by unique field

I am getting started with Strapi and have setup a basic model in the Strapi admin called page which looks like so:
page: {
title: Text (required)
slug: Text (required and unique)
}
As you can see it has a field called slug which is always unique. What I am wondering is how I can query by this field?
So far I have added 1 entry and when I launch graphql playground (at http://localhost:1337/graphql) I can get my entry returned via the following query:
query {
page(id:"1") {
title
}
}
When I try to query via slug as opposed to id like so:
query {
page(slug:"/") {
title
}
}
I am unable to do so even though it's a unique field. It does not even come up with the suggestions to use slug as a unique idetifier input inside the brackets. Why would this be?

MongoDB _id returns undefined on frontend (VueJS)

I created a simple fullstack webapp using NodeJS & Express + MongoDB to build the backend API and Vue.JS for the frontend.
All the Write Read and Delete API worked perfectly (I tested it using Postman). Everything works perfectly as well on the frontend, except when I tried to iterate (v-for) on an array of objects to get the _id, it doesn't work.
The array called posts has the attributes of 'text' and 'createdAt'. The v-for works perfectly and output the 2 attributes as expected. However, I tried to output _id (default id from MongoDB) but it returned "undefined".
This causes a problem because if I can't get _id, it wouldn't be possible for me to delete a specific post using the existing backend delete API.
From my understanding, in the backend side, the _id needs to be converted into ObjectId first before it can be used for db querying. But on the frontend (vue) I am not sure on how can turn _id into ObjectId. Am I getting into the right direction here?
<div class="post" v-for="(post,i) in posts " :key="post._id" :index="i" :item="post" #dblclick="deletePost(post._id)">
{{post.createdAt.getDate()}}/{{post.createdAt.getMonth() + 1}}/{{post.createdAt.getFullYear()}}
<p class="text">{{post.text}}</p>
</div>
...
methods: {
async deletePost(id){
console.log(id) //this returns undefined
await PostService.deletePost(id);
this.posts = await PostService.getPosts();
}
},
...
//del post in PostService.js
static deletePost(id){
return axios.delete(url+id)
}
//backend delete api
router.delete('/:id',async (req,res)=>{
const posts = await loadPostCollection()
console.log(ObjectID(req.params.id))
await posts.deleteOne({_id: ObjectID(req.params.id)});
res.status(200).send()
})
expected output: _id of each 'post', e.g:5cfa8c29f74c65ae485a6d93
actual output: undefined
no error message(s).
You need to add the property reference post, like this:
<div class="post" v-for="(post,i) in posts " :key="post._id" :post="post" #dblclick="deletePost(post._id)">
{{post.createdAt.getDate()}}/{{post.createdAt.getMonth() + 1}}/{{post.createdAt.getFullYear()}}
<p class="text">{{post.text}}</p>
</div>
You don't have to convert _id to Mongo ObjectID on the FrontEND.
Your code looks normal, send all post object to function like that and debug it.
#dblclick="deletePost(post)"
Probably your backend return _id as an object.

How to remove <br> tags from string in GraphQL query results

I'm working on a React application that utilizes Apollo and GraphQl to query an external API. My issue is that the data contains strings that have tags in them. I'd like to remove the tags.
The string looks like:
Additionally, Igor works as a driver for a transport company.<br /><br />The spring agricultural works on the land started already and he now supports more expenses.
My response data looks like 'data.loans.lend.values', and so I've tried using the str.replace() method on my data. However, it didn't work. I've probably spent about five hours combing through the web to find a solution, but haven't been able to.
This is what my Apollo query component looks like.
<Query query={kivaLoans} variables={{ country: country, sortBy: sort, limit: limitResults }}>
{({ data, loading, error }) => {
if (loading) return <div><p>Loading...</p></div>;
if (error) return <p>ERROR</p>;
return (
And this is my GraphQL query.
gql`
query ($country: [String], $sortBy: LoanSearchSortByEnum, $limit: Int) {
lend {
loans(filters: {status: fundraising, country: $country}, sortBy: $sortBy, limit: $limit) {
values {
id
plannedExpirationDate
image {
url(customSize: "s900")
}
name
loanFundraisingInfo {
fundedAmount
}
loanAmount
description
loanAmount
}
}
}
}`
Has anyone else encountered this issue before?
if you are receiving data back in a format you don't like, this means the graphql server, a database it leverages, or an api it leverages, is returning data to the graphql server in a format that isn't useful for you. The other possibility is that your server itself is formatting your data in an annoying way. So here are your options:
change your server / data sources as appropriate
do a global replace on the string returned: str.replace(/<b>/g, '').replace(/<\/b>/g, ''). Double check my escape characters, I may have that backwards.
in a string replace, /[what you want replaced]/g = a regex for global detection, across the entire string

Categories

Resources