Unable to use Fragments on GraphQL-yoga with Primsa












2















I am using graphql-yoga with Prisma and Prisma-Bindings



I'm trying to add a fragment to my resolver so that a specific field (id in this situation) is always fetched when the user asks for a custom field, costsToDate.



This is so i can make some additional queries needed to build the result for that field, and i need the ID of the object for that.



Unfortunatley i can't seem to get it to work, and the documentations seems a little lacking on the specifics with graphql-yoga and Prisma.



Here is the definition of the type:



type Job {
id: ID!
projectNumber: String!
client: Client!
name: String!
description: String
quoteNumber: String
workshopDaysQuoted: String!
quoted: String!
targetSpend: String!
costs: [JobCost!]!
estimatedCompletion: DateTime
completed: Boolean!
costTotal: String
workshopDaysUsed: String
costsToDate: String
}


And here is the resolver for the query:



const jobs = {
fragment: `fragment description on Jobs { id }`,
resolve: jobsResolver
}

async function jobsResolver(root, args, context, info) {
await validatePermission(args,context,info,['admin','user','appAuth'])
const {showCompleted} = args
const completedFilter = (typeof showCompleted === 'boolean') ? { completed: showCompleted } : {}
const jobIDS = await context.db.query.jobs({ where: completedFilter }, `{ id }`)
//console.log(jobIDS);
let jobs = await context.db.query.jobs({
where: completedFilter
}, info)
return await getAllJobCostsToDateList(jobs)
}


I am applying the the fragmentReplacements as per below.



const fragmentReplacements = extractFragmentReplacements(resolvers)

console.log(fragmentReplacements)

const port = process.env.PORT || 3010

const graphQLServer = new GraphQLServer({
typeDefs: './src/schema.graphql',
resolvers,
resolverValidationOptions: {
requireResolversForResolveType: false
},
context: req => ({
...req,
db: new Prisma({
typeDefs: `src/generated/prisma.graphql`,
fragmentReplacements,
endpoint: PRISMA_ENDPOINT,
secret: PRISMA_KEY,
debug: false
})
})
})


If i console.log the fragmentReplacements object i get the following, so it does seem to be picking up the fragments.



[ { field: 'job', fragment: 'fragment costsToDate on Job { id }' },
{ field: 'jobs',
fragment: 'fragment costsToDate on Jobs { id }' } ]


So my expectation here is that if i make a query against jobs or job that asks for the costsToDate field that it will also fetch the id for the job/each job.



However if i make the following query.



query{
jobs{
description
costsToDate
}
}


But i see no id fetched, and nothing in the root parameter on the resolver function.



Apologies as i am probably barking up completely the wrong tree here, seems like a somewhat simple requirement, but i can't quite work it out. Sure i'm missing something fundamental.



Thanks!



Gareth










share|improve this question



























    2















    I am using graphql-yoga with Prisma and Prisma-Bindings



    I'm trying to add a fragment to my resolver so that a specific field (id in this situation) is always fetched when the user asks for a custom field, costsToDate.



    This is so i can make some additional queries needed to build the result for that field, and i need the ID of the object for that.



    Unfortunatley i can't seem to get it to work, and the documentations seems a little lacking on the specifics with graphql-yoga and Prisma.



    Here is the definition of the type:



    type Job {
    id: ID!
    projectNumber: String!
    client: Client!
    name: String!
    description: String
    quoteNumber: String
    workshopDaysQuoted: String!
    quoted: String!
    targetSpend: String!
    costs: [JobCost!]!
    estimatedCompletion: DateTime
    completed: Boolean!
    costTotal: String
    workshopDaysUsed: String
    costsToDate: String
    }


    And here is the resolver for the query:



    const jobs = {
    fragment: `fragment description on Jobs { id }`,
    resolve: jobsResolver
    }

    async function jobsResolver(root, args, context, info) {
    await validatePermission(args,context,info,['admin','user','appAuth'])
    const {showCompleted} = args
    const completedFilter = (typeof showCompleted === 'boolean') ? { completed: showCompleted } : {}
    const jobIDS = await context.db.query.jobs({ where: completedFilter }, `{ id }`)
    //console.log(jobIDS);
    let jobs = await context.db.query.jobs({
    where: completedFilter
    }, info)
    return await getAllJobCostsToDateList(jobs)
    }


    I am applying the the fragmentReplacements as per below.



    const fragmentReplacements = extractFragmentReplacements(resolvers)

    console.log(fragmentReplacements)

    const port = process.env.PORT || 3010

    const graphQLServer = new GraphQLServer({
    typeDefs: './src/schema.graphql',
    resolvers,
    resolverValidationOptions: {
    requireResolversForResolveType: false
    },
    context: req => ({
    ...req,
    db: new Prisma({
    typeDefs: `src/generated/prisma.graphql`,
    fragmentReplacements,
    endpoint: PRISMA_ENDPOINT,
    secret: PRISMA_KEY,
    debug: false
    })
    })
    })


    If i console.log the fragmentReplacements object i get the following, so it does seem to be picking up the fragments.



    [ { field: 'job', fragment: 'fragment costsToDate on Job { id }' },
    { field: 'jobs',
    fragment: 'fragment costsToDate on Jobs { id }' } ]


    So my expectation here is that if i make a query against jobs or job that asks for the costsToDate field that it will also fetch the id for the job/each job.



    However if i make the following query.



    query{
    jobs{
    description
    costsToDate
    }
    }


    But i see no id fetched, and nothing in the root parameter on the resolver function.



    Apologies as i am probably barking up completely the wrong tree here, seems like a somewhat simple requirement, but i can't quite work it out. Sure i'm missing something fundamental.



    Thanks!



    Gareth










    share|improve this question

























      2












      2








      2








      I am using graphql-yoga with Prisma and Prisma-Bindings



      I'm trying to add a fragment to my resolver so that a specific field (id in this situation) is always fetched when the user asks for a custom field, costsToDate.



      This is so i can make some additional queries needed to build the result for that field, and i need the ID of the object for that.



      Unfortunatley i can't seem to get it to work, and the documentations seems a little lacking on the specifics with graphql-yoga and Prisma.



      Here is the definition of the type:



      type Job {
      id: ID!
      projectNumber: String!
      client: Client!
      name: String!
      description: String
      quoteNumber: String
      workshopDaysQuoted: String!
      quoted: String!
      targetSpend: String!
      costs: [JobCost!]!
      estimatedCompletion: DateTime
      completed: Boolean!
      costTotal: String
      workshopDaysUsed: String
      costsToDate: String
      }


      And here is the resolver for the query:



      const jobs = {
      fragment: `fragment description on Jobs { id }`,
      resolve: jobsResolver
      }

      async function jobsResolver(root, args, context, info) {
      await validatePermission(args,context,info,['admin','user','appAuth'])
      const {showCompleted} = args
      const completedFilter = (typeof showCompleted === 'boolean') ? { completed: showCompleted } : {}
      const jobIDS = await context.db.query.jobs({ where: completedFilter }, `{ id }`)
      //console.log(jobIDS);
      let jobs = await context.db.query.jobs({
      where: completedFilter
      }, info)
      return await getAllJobCostsToDateList(jobs)
      }


      I am applying the the fragmentReplacements as per below.



      const fragmentReplacements = extractFragmentReplacements(resolvers)

      console.log(fragmentReplacements)

      const port = process.env.PORT || 3010

      const graphQLServer = new GraphQLServer({
      typeDefs: './src/schema.graphql',
      resolvers,
      resolverValidationOptions: {
      requireResolversForResolveType: false
      },
      context: req => ({
      ...req,
      db: new Prisma({
      typeDefs: `src/generated/prisma.graphql`,
      fragmentReplacements,
      endpoint: PRISMA_ENDPOINT,
      secret: PRISMA_KEY,
      debug: false
      })
      })
      })


      If i console.log the fragmentReplacements object i get the following, so it does seem to be picking up the fragments.



      [ { field: 'job', fragment: 'fragment costsToDate on Job { id }' },
      { field: 'jobs',
      fragment: 'fragment costsToDate on Jobs { id }' } ]


      So my expectation here is that if i make a query against jobs or job that asks for the costsToDate field that it will also fetch the id for the job/each job.



      However if i make the following query.



      query{
      jobs{
      description
      costsToDate
      }
      }


      But i see no id fetched, and nothing in the root parameter on the resolver function.



      Apologies as i am probably barking up completely the wrong tree here, seems like a somewhat simple requirement, but i can't quite work it out. Sure i'm missing something fundamental.



      Thanks!



      Gareth










      share|improve this question














      I am using graphql-yoga with Prisma and Prisma-Bindings



      I'm trying to add a fragment to my resolver so that a specific field (id in this situation) is always fetched when the user asks for a custom field, costsToDate.



      This is so i can make some additional queries needed to build the result for that field, and i need the ID of the object for that.



      Unfortunatley i can't seem to get it to work, and the documentations seems a little lacking on the specifics with graphql-yoga and Prisma.



      Here is the definition of the type:



      type Job {
      id: ID!
      projectNumber: String!
      client: Client!
      name: String!
      description: String
      quoteNumber: String
      workshopDaysQuoted: String!
      quoted: String!
      targetSpend: String!
      costs: [JobCost!]!
      estimatedCompletion: DateTime
      completed: Boolean!
      costTotal: String
      workshopDaysUsed: String
      costsToDate: String
      }


      And here is the resolver for the query:



      const jobs = {
      fragment: `fragment description on Jobs { id }`,
      resolve: jobsResolver
      }

      async function jobsResolver(root, args, context, info) {
      await validatePermission(args,context,info,['admin','user','appAuth'])
      const {showCompleted} = args
      const completedFilter = (typeof showCompleted === 'boolean') ? { completed: showCompleted } : {}
      const jobIDS = await context.db.query.jobs({ where: completedFilter }, `{ id }`)
      //console.log(jobIDS);
      let jobs = await context.db.query.jobs({
      where: completedFilter
      }, info)
      return await getAllJobCostsToDateList(jobs)
      }


      I am applying the the fragmentReplacements as per below.



      const fragmentReplacements = extractFragmentReplacements(resolvers)

      console.log(fragmentReplacements)

      const port = process.env.PORT || 3010

      const graphQLServer = new GraphQLServer({
      typeDefs: './src/schema.graphql',
      resolvers,
      resolverValidationOptions: {
      requireResolversForResolveType: false
      },
      context: req => ({
      ...req,
      db: new Prisma({
      typeDefs: `src/generated/prisma.graphql`,
      fragmentReplacements,
      endpoint: PRISMA_ENDPOINT,
      secret: PRISMA_KEY,
      debug: false
      })
      })
      })


      If i console.log the fragmentReplacements object i get the following, so it does seem to be picking up the fragments.



      [ { field: 'job', fragment: 'fragment costsToDate on Job { id }' },
      { field: 'jobs',
      fragment: 'fragment costsToDate on Jobs { id }' } ]


      So my expectation here is that if i make a query against jobs or job that asks for the costsToDate field that it will also fetch the id for the job/each job.



      However if i make the following query.



      query{
      jobs{
      description
      costsToDate
      }
      }


      But i see no id fetched, and nothing in the root parameter on the resolver function.



      Apologies as i am probably barking up completely the wrong tree here, seems like a somewhat simple requirement, but i can't quite work it out. Sure i'm missing something fundamental.



      Thanks!



      Gareth







      graphql apollo-server prisma






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 8:51









      Gareth JeanneGareth Jeanne

      67521329




      67521329
























          1 Answer
          1






          active

          oldest

          votes


















          0














          A fragment is used to always retrieve given fields on a given type.



          It follows the following format:



          fragment NameOfYourFragment on YourType { ... }


          You currently can't apply a given fragment conditionally as it is always applied.
          Moreover, you specified a fragment on Jobs, but the type name used by Prisma is Job (even if you have the job and jobs resolvers)



          You probably only need the following resolver:



          const job = {
          fragment: `fragment JobId on Job { id }`,
          resolve: jobsResolver
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53427037%2funable-to-use-fragments-on-graphql-yoga-with-primsa%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            A fragment is used to always retrieve given fields on a given type.



            It follows the following format:



            fragment NameOfYourFragment on YourType { ... }


            You currently can't apply a given fragment conditionally as it is always applied.
            Moreover, you specified a fragment on Jobs, but the type name used by Prisma is Job (even if you have the job and jobs resolvers)



            You probably only need the following resolver:



            const job = {
            fragment: `fragment JobId on Job { id }`,
            resolve: jobsResolver
            }





            share|improve this answer




























              0














              A fragment is used to always retrieve given fields on a given type.



              It follows the following format:



              fragment NameOfYourFragment on YourType { ... }


              You currently can't apply a given fragment conditionally as it is always applied.
              Moreover, you specified a fragment on Jobs, but the type name used by Prisma is Job (even if you have the job and jobs resolvers)



              You probably only need the following resolver:



              const job = {
              fragment: `fragment JobId on Job { id }`,
              resolve: jobsResolver
              }





              share|improve this answer


























                0












                0








                0







                A fragment is used to always retrieve given fields on a given type.



                It follows the following format:



                fragment NameOfYourFragment on YourType { ... }


                You currently can't apply a given fragment conditionally as it is always applied.
                Moreover, you specified a fragment on Jobs, but the type name used by Prisma is Job (even if you have the job and jobs resolvers)



                You probably only need the following resolver:



                const job = {
                fragment: `fragment JobId on Job { id }`,
                resolve: jobsResolver
                }





                share|improve this answer













                A fragment is used to always retrieve given fields on a given type.



                It follows the following format:



                fragment NameOfYourFragment on YourType { ... }


                You currently can't apply a given fragment conditionally as it is always applied.
                Moreover, you specified a fragment on Jobs, but the type name used by Prisma is Job (even if you have the job and jobs resolvers)



                You probably only need the following resolver:



                const job = {
                fragment: `fragment JobId on Job { id }`,
                resolve: jobsResolver
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 29 '18 at 10:12









                ErrornameErrorname

                800217




                800217
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53427037%2funable-to-use-fragments-on-graphql-yoga-with-primsa%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                    Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                    A Topological Invariant for $pi_3(U(n))$