GraphQL schema from a single object JSON file in Gatsby

时间秒杀一切 提交于 2019-12-10 19:57:53

问题


So I'd like to query a single JSON file which is not an array from Gatsby's GraphQL but I don't really know how to do it.

As far as I understand gatsby-transformer-json docs - it only supports loading arrays and have them accessible via allFileNameJson schema.

My gatsby-config plugins (only the necessary ones for this question):

{
  resolve: 'gatsby-source-filesystem',
  options: {
    name: 'data',
    path: `${__dirname}/src/data`
  }
},
'gatsby-transformer-json'

And then let's say in src/data i have a something.json file, like this:

{
  "key": "value"
}

Now I'd like to query the data from something.json file, but there is no somethingJson schema i can query (tried with Gatsby's GraphiQL).

Could someone point out what am I doing wrong or how can I solve this problem?


回答1:


Ok, so it is possible to query single-object files as long as they have a parent (folder).

Let's take these parameters:

  • gatsby-source-filesystem configured to src/data
  • test.json file positioned at src/data/test.json with { "key": "value" } content in it

Now as the test.json file actually has a parent (data folder) - you can query the fields from test.json like this:

{
  dataJson {
    key
  }
}

But putting those directly in your root folder is a bad practice, because when you will store another json file, i.e. secondtest.json with { "key2": "value2" } content, and will query it with the same query as above, you will get data only from a single node (not sure if it takes first, or last encountered node),

So, the perfect solution for this case is to have your single-object json files stored in separate folders with just one json per folder.

For example you have some "About Me" data:

  1. create a about folder in your src/data
  2. create an index.json file with i.e. { "name": "John" }
  3. query your data

Like this:

{
  aboutJson {
    name
  }
}

That's it.



来源:https://stackoverflow.com/questions/50370196/graphql-schema-from-a-single-object-json-file-in-gatsby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!