Nuxt3 Plugin Strapi: How to return only one result using FindOne with populate parameter? - strapi

Using Nuxt3 and the Strapi v4 Plugin to create a blog.
Using the findOne function to retrieve ONE article.
However using the populate parameter to also retrieve relational parameters such as images:
findOne<Article>('articles', { populate: "images"}, id)
returns a list of ALL articles.
I want only my one article!
How do I get only the result for my given ID including the relations (images) when using the findOne function with the populate paramter?
Docs I consulted:
Strapi Docs on Parameters: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest/populating-fields.html#field-selection
Strapi Nuxt Docs: https://strapi.nuxtjs.org/usage

Your query syntax is wrong. findOne takes id as the second parameter and options as the third parameter as below:
Syntax:
findOne(uid: string, id: ID, parameters: Params) ⇒ Entry
Solution in Strapi:
const entry = await strapi.entityService.findOne('api::article.article', 1, {
fields: ['title', 'description'],
populate: { category: true },
});
Solution in Nuxt Strapi:
const entry = await findOne<Article>('articles', 1, {
fields: ['title', 'description'],
populate: { images: true },
});
Reference:
Entity Service Api
findOne - Nuxt Strapi

Related

Implement cursor based pagination using pothos and prisma

Is there any way to implement cursor-based pagination using the pothos Prisma plugin, I'm referring to this plugin .but there is no clear example of how to do the pagination. The documentation is somewhat difficult to understand. this is the Prisma model I want for the pagination
Prisma Model
model user {
id String #id #map("_id")
factories factory[]
##map("user")
}
Pothos Model
builder.prismaObject("user", {
fields: (t) => ({
id: t.exposeID("id"),
factories:t.relation("factories")
}),
});
I figured out the way to do the cursor-based pagination using pothos. you just have to add the prismaConnection to the query field
builder.queryField("users", (t) =>
t.prismaConnection({
type: "user",
cursor: "id",
resolve: async (query, _root, _args, _ctx, _infu) => {
// add the relevant cursors-based Prisma pagination logic
// here.you can refer to the Prisma
// doc for more info
return await db.user.findMany({ ...query });
},
})
);
this will automatically add all the cursours,edges,nodes and pageInfo Objects to the response

Apollo GraphQL query refetch

I'm trying to do a query refetch after a form submission using Apollo. I am trying to use this example: https://www.apollographql.com/docs/react/data/queries/#refetching
My query is:
const { data: accountData, loading: accountLoading, refetch: accountDataRefetch } = useGetUserSocialLoginQuery({ variables: { accountId: nrId } })
After the form submission I'm calling the refetch function:
const formSubmissionFunction = async () => {
// update an UserSocialLogin entity
await accountDataRefetch()
}
I've also tried to update the query result within the update mutation, but also without success. The UserSocialLogin entity is updated but the data object remains the same. The UI should display the new data.
Do you have any ideas?

Graphql sending empty string

I am using graphql to get some data.
let { loading, error, data } = useQuery(GET_JOBS_SEARCH, {
variables: {
category: category,
type: jobType
}
});
Now when I update the category the API gets called with variables like
variables: {category: "leadership", type: ""}
Now I don't want the type:'' in my call.

Apollo-client: Add item to array in cache

Suppose I have the following GraphQL types:
type User {
id: String!
posts: [Post!]!
}
type Post {
id: String!
text: String,
}
And here is a mutation that returns the updated post:
mutation addNewPost(
$userId: String!
$text: String!
) {
addNewPost(userId: $userId, text: $text) {
id
text
}
}
After running this mutation my cache contains a new entry of a post. How do I add it to the user's posts array? I have tried cache.writeQuery and cache.modify but I cannot figure it out.
We do push the item into array inside the update function, which is one of the options of useMutation.
I'm writing the whole mutation so that you can get the idea 💡, let have a look at example:
By Update function:
const [createPost, { data, loading, error }] = useMutation(CREATE_POST, {
update(cache, response) {
// Here we write the update
// Step 1: Read/Fetch the data 👈
const data = client.readQuery({
query: FETCH_POSTS_QUERY,
});
// Step 2: Update the cache by immutable way 👈
client.writeQuery({
query: FETCH_POSTS_QUERY,
data: {
getPosts: [response.data.createPost, ...data.getPosts],
},
});
},
variables: formValues,
});
By refetchQueries:
That's really shortcut 🔥 way to update the cache, by using DocumentNode object parsed with the gql function
const [createPost, { data, loading, error }] = useMutation(CREATE_POST, {
refetchQueries: [ 👈
FETCH_POSTS_QUERY
'fetchPosts`' // OR Query name
],
variables: formValues,
});
You're going to want to directly write to the Apollo cache in order to update the other entities that your mutation has modified.
Have a look at the docs https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates here for specifics (you're going to want to use cache.modify and cache.writeFragment)

Unable to call lifecycle methods in Strapi models?

I have a Strapi project with a MongoDB database and a simple Post model. This model has, among others, a slug field with the following attributes:
type: string,
unique: true,
required: true
For testing purposes, I am attempting to modify this field's value before committing it to the DB, via one of Strapi's lifecycle methods:
module.exports = {
// Before saving a value.
// Fired before an `insert` or `update` query.
beforeSave: async (model) => {
// Set the password.
const newslug = model.slug + '-test';
model.slug = newslug;
},
};
But the method just doesn't seem to get fired as expected when I save a post on my admin page. The post, along with its slug, gets upserted to the DB without the modification shown in the code above. Am I misunderstanding the functionality?
If you are using NoSQL database (Mongo)
beforeSave: async (model) => {
if (model.content) {
model.wordCount = model.content.length;
}
},
beforeUpdate: async (model) => {
if (model.getUpdate().content) {
model.update({
wordCount: model.getUpdate().content.length
});
}
},
If you are using SQL (SQLite, Postgres, MySQL)
beforeSave: async (model, attrs, options) => {
if (attrs.content) {
attrs.wordCount = attrs.content.length;
}
},

Resources