Implement cursor based pagination using pothos and prisma - graphql

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

Related

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

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

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?

react-admin dataprovider specify a custom field as primary key - a field that is not named "id"

I'm using the hasura data provider in react-admin ra-data-hasura (but i'm sure its more or less the same thing of ra-data-graphql)
My entity has their primary keys that are named differently from id
Is it possible to set a field as primary that is not named id Eg: MyEntityId
Is it possible to specifiy it resource by resource (because each table could have its own name pattern) or globally
Alex,
You have that answer in the docs: https://marmelab.com/react-admin/FAQ.html#can-i-have-custom-identifiersprimary-keys-for-my-resources
you have to resolve this at the dataProvider level.
You have to implement your own dataProvider's methods that mapped your MyEntityId field to the id field required by react-admin.
For example (implementing getList method):
const myDataProvider = {
getList: (resource, params) => {
return fetch(API_URL)
.then(({ json }) => ({
data: json.map((record) => ({ id: record.MyEntityId, ...record })),
total: parseInt(json.total, 10),
})
);
}
//...
}
json.map(record => ({"id": record.userID, ...record})),
Yes, you can customize the cache IDs using the keyFields for each type in the typePolicies option of the InMemoryCache constructor:
const client = new ApolloClient({
...
cache: new InMemoryCache({
typePolicies: {
MyEntity1: {
keyFields: ["MyEntityId"],
},
MyEntity2: {
keyFields: ["MyEntityId"],
},
...
}
}),
...
})
buildHasuraProvider({ client });

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;
}
},

Pass ID from React to Apollo to find correct result?

Im using React with Apollo (Apollo Client v2). I have group query which needs to return a single group.
This code is working but I've hard coded HARD-CODED-ID. How can I instead pass the ID as a string from the React component?
In my React component:
const groupQuery = gql`
query Group {
group {
_id
name
}
}
`;
export default graphql(groupQuery, {
props: ({ data }) => ({ ...data }),
})(GroupPage);
My resolver:
Query: {
groups() {
return Groups.find().fetch();
},
group() {
return Groups.findOne('HARD-CODED-ID');
},
}
There's three things that you'll need to do:
1.) If you haven't already, modify the schema on your server so that your query accepts the id as an input, for example:
type Query {
#other queries
group(id: ID!): Group
}
2.) Modify your resolver so that it handles the passed-in id. Assuming you're using graphql-tools:
group(root, { id }) {
return Groups.findOne(id); // did you mean something like findOne({id}) ?
},
3.) Modify your client-side code. Typically, you'll make the id a prop you pass in to your component, and then use that as a variable in your request.
const groupQuery = gql`
query Group($id: ID!) {
group(id: $id) {
_id
name
}
}
`;
// assuming that the component prop is called groupId
export default graphql(groupQuery, {
options: ({ groupId }) => ({
variables: { id: groupId },
}),
})(GroupPage);
Instead of an object, options can be a function, in which case it's passed the component's props as its first parameter. You can then use those props to define the variables your query will use. You can read more about using variables with Apollo client here and here.

Resources