Gatsby - runQuery inside createResolver using group - graphql

I would like to use createResolvers to run a query using group, but I don't think this is possible at the moment. According to Accessing Gatsby’s data store from field resolvers, it seems runQuery currently accepts filter and sort query arguments, but not group. I was hopeful that runQuery would support group (based on https://github.com/gatsbyjs/gatsby/issues/15453), but I can't find any examples of grouping using runQuery
If possible, how can I use createResolvers to run a query using group for the following graphql query?
query {
allFile(filter: { internal: { mediaType: { eq: "text/markdown" } } }) {
group(field: sourceInstanceName) {
fieldValue
totalCount
}
}
}
For context, I have 2 folders (coding & recipes) that I am sourcing markdown files from. Here is my gatsby-config.js:
const path = require('path')
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `coding`,
path: path.resolve(__dirname, `src/contents/coding`),
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `recipes`,
path: path.resolve(__dirname, `src/contents/recipes`),
},
},
{
resolve: `gatsby-transformer-remark`,
},
],
}
Currently, I am able to use runQuery to run queries using filter. Here is my gatsby-node.js:
exports.createResolvers = ({ createResolvers }) => {
createResolvers({
Query: {
recipes: {
type: `[File!]!`,
resolve(source, args, context, info) {
return context.nodeModel.runQuery({
query: {
filter: {
internal: { mediaType: { eq: 'text/markdown' } },
sourceInstanceName: { eq: 'recipes' },
},
},
type: `File`,
firstOnly: false,
})
},
},
coding: {
type: `[File!]!`,
resolve(source, args, context, info) {
return context.nodeModel.runQuery({
query: {
filter: {
internal: { mediaType: { eq: 'text/markdown' } },
sourceInstanceName: { eq: 'coding' },
},
},
type: `File`,
firstOnly: false,
})
},
},
},
})
}
But now I want to use createResolver to runQuery using group. Is this possible? If so, how?
I've produced a minimal repo at https://github.com/kimbaudi/gatsby-group-query
Currently, the home page (src/pages/index.jsx) is displaying the folders (coding & recipes) and the count of markdown files in that folder:
using the following page query:
export const query = graphql`
query {
allFile(filter: { internal: { mediaType: { eq: "text/markdown" } } }) {
group(field: sourceInstanceName) {
fieldValue
totalCount
}
}
}
`
and I would like to create a resolver that groups and use it in place of the above page query.

Related

How to implement a filter on a query in Apollo?

I'm attempting to filter a query by a specific field. I can achieve this in Apollo explorer in dev tools but I can't seem to translate this into code.
The following works in Apollo explorer:
query ListUsersByType($filter: TableUsersFilterInput) {
listUsers(filter: $filter) {
items {
email
id
type
}
}
}
{
"filter": {
"type": {
"eq": "ADMIN"
}
}
}
I am unsure how this translates to the code using the useQuery hook however.
When I try the following it doesn't filter the list at all, it just fetches all of them regardless of type:
const ListUsersByType = gql`
query ListUsersByType($type: TableUsersFilterInput) {
listUsers(filter: $type) {
items {
email
id
type
}
}
}
`
const { data, loading, error } = useQuery(ListUsersByType, {
variables: {
filter: {
type: {
eq: 'ADMIN',
},
},
},
})
What am I missing here?
Your names are not correct
Here you say filter will use the variable type
const ListUsersByType = gql`
query ListUsersByType($type: TableUsersFilterInput) {
listUsers(filter: $type) {
items {
email
id
type
}
}
}
`
And here you pass filter
const { data, loading, error } = useQuery(ListUsersByType, {
variables: {
filter: {
type: {
eq: 'ADMIN',
},
},
},
})
You can
First solution
replace $type by $filter
const ListUsersByType = gql`
query ListUsersByType($filter: TableUsersFilterInput) {
listUsers(filter: $filter) {
items {
email
id
type
}
}
}
`
Second solution
rename the variable filter to type
const { data, loading, error } = useQuery(ListUsersByType, {
variables: {
type: {
type: {
eq: 'ADMIN',
},
},
},
})
My opinion
I let you choose but the first option seems the best

Gatsby & Graphql: Filter allMarkdownRemark for pages matching a variable

I'm trying to filter all my markdown pages, for pages which match a certain category(specified in markdown frontmatter) and pages which are not the pages being currently visited. All pages created from markdown though are receiving the same result for allMarkdownRemark though and are not filtering any results.
I would like to know how to get all the pages to not have the same result for allMarkdownRemark, and would like the results in allMarkdownRemark to be filtered
My page query looks something like
export const pageQuery = graphql`
query ArticleQuery($path: String, $category: String, $title: String) {
allMarkdownRemark(
filter: {
frontmatter: {
category: {eq: $category},
title: {ne: $title}
}
},
sort: {
order: DESC, fields: [frontmatter___date]
}
) {
...
And my gatsby-node.js looks like
const { createFilePath } = require(`gatsby-source-filesystem`);
const { fmImagesToRelative } = require('gatsby-remark-relative-images-v2');
const path = require("path");
exports.createPages = async ({ actions: { createPage }, graphql }) => {
const postTemplate = path.resolve(`src/components/ArticlePage.jsx`);
const result = await graphql(`
{
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___title] }
) {
edges {
node {
fields {
slug
}
frontmatter {
category
title
}
}
}
}
}
`);
if (result.errors) {
return Promise.reject(result.errors);
};
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: `${node.fields.slug}`,
category: `${node.frontmatter.category}`,
title: `${node.frontmatter.title}`,
component: postTemplate,
context: {node}
});
});
};
exports.onCreateNode = ({ node, getNode, actions }) => {
fmImagesToRelative(node);
if (node.internal.type === `MarkdownRemark`){
actions.createNodeField({
node,
name: `slug`,
value: createFilePath({ node, getNode, basePath: `pages`, trailingSlash: true }),
});
}
};
All markdown files include something like this in them
---
title: "My title"
category: "My category"
---
I would like to know how to get all the pages to not have the same
result for allMarkdownRemark, and would like the results in
allMarkdownRemark to be filtered
In these cases, what is commonly used is a key field for all kind of markdown files that you want to group. As you said, allMarkdownRemark is a schema inferred by Gatsby (and their transformers and sharps) at the time that you allow it to access to your filesystem so you can't distinguish directly the type of markdown. This is the simplest, cleanest, and less invasive option. You just need to:
---
title: "My title"
category: "My category"
key: "pageTypeOne"
---
Then, in your queries, you just need to filter for key field when needed:
export const pageQuery = graphql`
query ArticleQuery($path: String, $category: String, $title: String) {
allMarkdownRemark(
filter: {
frontmatter: {
category: {eq: $category},
title: {ne: $title}
key: {eq: "pageTypeOne" }
}
},
sort: {
order: DESC, fields: [frontmatter___date]
}
) {
...
You can change the string-based approach to a context one if needed in your createPage API in your gatsby-node.js. Or, depending on your needs, create a filtered query in your gatsby-node.js, creating different queries for each page, in that way your markdownRemark will be filtered already.
Alternatively, you can add different filesystems (gatsby-source-filesystem) and use the inferred sourceInstanceName to get your data:
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages/`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `posts`,
path: `${__dirname}/src/posts/`,
},
},
Then:
{
allFile(filter: { sourceInstanceName: { eq: "posts" } }) {
edges {
node {
extension
dir
modifiedTime
}
}
}
}

Prisma2: How to solve n +1 Problem with Paljs

thx for any help.
Im using at the frontend the apollo-client and at the backend graphql-nexus,prisma2 and graphql-yoga server.
I want to solve the n + 1 problem with #paljs/plugins.
At the frontend I have a query posts like:
query posts{
posts {
id
favoritedBy(where: { id: { equals: $currentUserId } }) {
id
}
author {
id
avatar {
id
}
}
link {
id
}
games {
id
}
tags {
id
}
likes(where: { user: { id: { equals: $currentUserId } } }) {
id
}
}
}
Posts resolver:
import { PrismaSelect } from '#paljs/plugins'
export const posts = queryField('posts', {
type: 'Post',
list: true,
args: {
...
},
resolve: async (_parent, args, { prisma, request }, info) => {
const select = new PrismaSelect(info).value
let opArgs: FindManyPostArgs = {
take: 10,
orderBy: {
[args.orderBy]: 'desc',
},
...select
}
const post = await prisma.post.findMany(opArgs)
//The result I want to return with the "sub-models" like likes, author tags...
console.log(JSON.stringify(post, undefined, 2))
return post
},
})
I logging the queries
const prisma = new PrismaClient({
log: ['query'],
})
My Problem: With PrismaSelect, I have 5 queries more than without and If I check the request-time at the frontend I need 300-400ms longer with PrismaSelect. So what I'm doing wrong?
I saw in the #paljs/plugins doc the select in the context. Maybe that is my mistake. How can I use the select in the context?
Here ist my Context:
import { PrismaClient, PrismaClientOptions } from '#prisma/client'
import { PubSub } from 'graphql-yoga'
import { PrismaDelete, onDeleteArgs } from '#paljs/plugins'
class Prisma extends PrismaClient {
constructor(options?: PrismaClientOptions) {
super(options)
}
async onDelete(args: onDeleteArgs) {
const prismaDelete = new PrismaDelete(this)
await prismaDelete.onDelete(args)
}
}
export const prisma = new PrismaClient({
log: ['query'],
})
export const pubsub = new PubSub()
export interface Context {
prisma: PrismaClient
request: any
pubsub: PubSub
}
export function createContext(request: any): Context {
return { prisma, request, pubsub }
}
You need to know that to use my PrismaSelect plugin you need to remove the nexus-prisma-plugin package and use my Pal.js CLI to create your CRUD and ObjectType for nexus and using #paljs/nexus plugin to add in mackSchema function
import { makeSchema } from '#nexus/schema';
import * as types from './graphql';
import { paljs } from '#paljs/nexus'; // import our plugin
export const schema = makeSchema({
types,
plugins: [paljs()],// here our plugin don't use nexus-prisma-plugin
outputs: {
schema: __dirname + '/generated/schema.graphql',
typegen: __dirname + '/generated/nexus.ts',
},
typegenAutoConfig: {
sources: [
{
source: require.resolve('./context'),
alias: 'Context',
},
],
contextType: 'Context.Context',
},
});
Now add this type to your Context
export interface Context {
prisma: PrismaClient
request: any
pubsub: PubSub
select: any // here our select type
}
export function createContext(request: any): Context {
// our paljs plugin will add select object before resolver
return { prisma, request, pubsub, select: {} }
}
after you add our plugin your query will log like this
extendType({
type: 'Query',
definition(t) {
t.field('findOneUser', {
type: 'User',
nullable: true,
args: {
where: arg({
type: 'UserWhereUniqueInput',
nullable: false,
}),
},
resolve(_, { where }, { prisma, select }) {
// our plugin add select object into context for you
return prisma.user.findOne({
where,
...select,
});
},
});
},
});
Can you please try to use my pal c command to start an example from my list and try your schema and make tests with it
It is working, thx Ahmed your plugin is AWESOME!!!!!
I changed my Post-Object from
const Post = objectType({
name: 'Post',
definition(t) {
t.model.id()
t.model.authorId()
t.model.tags()
t.model.games()
t.model.link()
t.model.report()
t.model.notifications()
t.model.author()
t.model.favoritedBy({
filtering: {
id: true,
},
})
t.model.likes({
filtering: {
user: true,
},
})
}
})
to
const Post = objectType({
name: 'Post',
definition(t) {
t.string('id')
t.field('tags', {
nullable: false,
list: [true],
type: 'Tag',
resolve(parent: any) {
return parent['tags']
},
})
t.field('games', {
list: [true],
type: 'Game',
resolve(parent: any) {
return parent['games']
},
})
t.field('link', {
type: 'Link',
nullable: true,
resolve(parent: any) {
return parent['link']
},
})
t.field('notifications', {
list: [true],
type: 'Notification',
resolve(parent: any) {
return parent['notifications']
},
})
t.field('author', {
nullable: false,
type: 'User',
resolve(parent: any) {
return parent['author']
},
})
t.field('favoritedBy', {
nullable: false,
list: [true],
type: 'User',
args: {
where: 'UserWhereInput',
},
resolve(parent: any) {
return parent['favoritedBy']
},
})
t.field('likes', {
list: [true],
type: 'Like',
args: {
where: 'LikeWhereInput',
},
resolve(parent: any) {
return parent['likes']
},
})
},
})
And I also used the nexus-prisma-plugin and paljs-plugin at the same time

How can GraphQL enable an ID based query at sub fields level?

If an existing service supporting the following GraphQL queries respectively:
query to a person's bank account:
query {
balance(id: "1") {
checking
saving
}
}
result
{
"data": {
"balance": {
"checking": "800",
"saving": "3000"
}
}
}
query to a person's pending order:
query {
pending_order(id: "1") {
books
tickets
}
}
result
{
"data": {
"pending_order": {
"books": "5",
"tickets": "2"
}
}
}
The source code achieving the above functionality is something like this:
module.exports = new GraphQLObjectType({
name: 'Query',
description: 'Queries individual fields by ID',
fields: () => ({
balance: {
type: BalanceType,
description: 'Get balance',
args: {
id: {
description: 'id of the person',
type: GraphQLString
}
},
resolve: (root, { id }) => getBalance(id)
},
pending_order: {
type: OrderType,
description: 'Get the pending orders',
args: {
id: {
description: 'id of the person',
type: GraphQLString
}
},
resolve: (root, { id }) => getPendingOrders(id)
}
})
});
Now, I want to make my GraphQL service schema support person level schema, i.e.,
query {
person (id: "1") {
balance
pending_order
}
}
and get the following results:
{
"data": {
"balance": {
"checking": "800",
"saving": "3000"
}
"pending_order": {
"books": "5",
"tickets": "2"
}
}
}
How can I re-structure the schema, and how can I reuse the existing query service?
EDIT (after reading Daniel Rearden's answer):
Can we optimize the GraphQL service so that we make service call based upon the query? i.e., if the incoming query is
query {
person (id: "1") {
pending_order
}
}
my actually query becomes
person: {
...
resolve: (root, { id }) => Promise.all([
getBalance(id)
]) => ({ balance})
}
You're going to have to define a separate Person type to wrap the balance and pending_order fields.
module.exports = new GraphQLObjectType({
name: 'Person',
fields: () => ({
balance: {
type: BalanceType,
resolve: ({ id }) => getBalance(id)
},
pending_order: {
type: OrderType,
resolve: ({ id }) => getPendingOrders(id)
}
})
});
And you're going to need to add a new field to your Query type:
person: {
type: PersonType,
args: {
id: {
type: GraphQLString
}
},
// We just need to return an object with the id, the resolvers for
// our Person type fields will do the result
resolve: (root, { id }) => ({ id })
}
There's not much you can do to keep things more DRY and reuse your existing code. If you're looking for a way to reduce boilerplate, I would suggest using graphql-tools.

Filters in GraphQL

const { connectionType: PersonConnection } = connectionDefinitions({
name: 'Person',
nodeType: PersonType,
here i am using connectionFields for count
connectionFields: {
count: {
type: GraphQLInt,
resolve: (args) => {
const filter = args.args || {};
return Person.count(filter).exec();
},
},
},
});
i am quite confused about using args with custom filters and obtain data from database, using filter
if i don't provide any id count should provide all data count, if i provide any id it may also look for references data and search in another models so how to perform the count and efficient filteration of data.
Thanks in Advance
person: {
type: PersonConnection,
args: _.assign({
_id: { type: GraphQLID },
// assign mine custom filters
name: { type: GraphQLString },
location: { type: GraphQLString },
education: { type: GraphQLString },
}, connectionArgs),
resolve: (obj, args, auth, fieldASTs) => {
const filter = args;
return connectionFromPromisedArray(getPersons(filter, fieldASTs), args).then((data) => {
// using to connection Fields
data.args = filter;
return data;
}).catch(err => new Error(err));
},
},

Resources