Gridsome Pages API - pass object/array in context

Viewed 576

I'm new to Gridsome (and GraphQL) and I'd like to build the following. I have a n-to-n relationship of Employees to Projects and would like to generate a page per employee, listing all the projects this employee worked on. I create the pages using the Pages API, which is the part that does work. However, passing the context / listing the projects per employee doesn't work.

All the data is in markup and looks like this: Projects:

---
name: "Project 1"
...
---

Employees:

---
name: "Employee 1" 
projects:
  - name: "Project 1"
  - name: "Project 2"
---

gridsome.server.js:

  api.createPages(async ({ graphql, createPage }) => {
    const { data } = await graphql(`{
      allEmployee {
        edges {
          node {
            id
            name
            projects {
               name 
            }
          }
        }
      }
    }`)

    data.allEmployee.edges.forEach(({ node }) => {
      createPage({
        path: `/${node.name}`,
        component: './src/templates/Employee.vue',
        context: {
          id: node.id,
          name: node.name,
          projectsWorkedOn: node.projects
        }
      })
    })
  })

page-query in Employee.vue:

<page-query>
query EmployeeProjects ($projectsWorkedOn: [String]) {
  allProject (filter: { name: { in: $projectsWorkedOn } } ) { //how to use the $projectsWorkedOn object here?
        edges {
        node {
          id
          name
      }
    }
  }
}
</page-query>

Now that doesn't work, at the very least I'm trying to use the object as an array, but I'm sure there are other things wrong with it as well. I hope someone can point me in the right direction, unfortunately Gridsome documentation is quite shallow.

1 Answers

While I didn't get the filter to work, I do have a solution for my use-case. Pretty basic stuff, but since most Gridsome questions remain unanswered on stackoverflow I post it in the hope someone finds it useful.

Instead of filtering in the page query I just query everything

<page-query>
query 
  projects { allProject {
        edges {
        node {
          id
          title
          content

      }
    }
  }
}
</page-query>

and then get what I want with a helper function:

<script>
export default {
    methods: {
    getProjectDetails(id) {
            return this.$page.allProject.edges.filter(edge => {
        return edge.node.id === id
      })
    }
  }
}
</script>

that I can use in the template like this:

<span v-for="project in $context.projects" :key="project.id">
    {{ getProjectDetails(project.id)[0].node.title }}
...
Related