Skip to content

Commit

Permalink
fix: Get parent not root File node in resolver (gatsbyjs#13289)
Browse files Browse the repository at this point in the history
In the `fileByPath` resolver, we need a node's parent `File` node to resolve relative to absolute paths. For this we use `findRootNodeAncestor`, which will return a node's root node. This can be problematic for (unusual) scenarios like in gatsbyjs#13267 where a node has more than one `File` node ancestor. We should just use the closest `File` parent.

Fixes gatsbyjs#13267
  • Loading branch information
stefanprobst authored and pieh committed Apr 11, 2019
1 parent 52b4f3c commit 8031fcf
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
51 changes: 51 additions & 0 deletions packages/gatsby/src/schema/__tests__/queries-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,30 @@ const nodes = [
dir: basePath,
absolutePath: filePath(`test.txt`),
},
{
id: `file4`,
parent: `file5`,
children: [`test2`],
internal: {
type: `File`,
contentDigest: `file4`,
},
name: `parent.txt`,
dir: basePath,
absolutePath: filePath(`parent.txt`),
},
{
id: `file5`,
parent: null,
children: [`file4`],
internal: {
type: `File`,
contentDigest: `file5`,
},
name: `root.txt`,
dir: `/`,
absolutePath: `/root.txt`,
},
{
id: `test1`,
parent: `file3`,
Expand All @@ -71,6 +95,15 @@ const nodes = [
},
],
},
{
id: `test2`,
parent: `file4`,
children: [],
internal: {
type: `TestChild`,
},
file: `./1.png`,
},
]

describe(`Query fields of type File`, () => {
Expand Down Expand Up @@ -189,4 +222,22 @@ describe(`Query fields of type File`, () => {
expect(results.errors).toBeUndefined()
expect(results.data).toEqual(expected)
})

it(`uses nearest File node ancestor to resolve relative paths`, async () => {
const query = `
{
testChild {
file { name }
}
}
`
const results = await runQuery(query)
const expected = {
testChild: {
file: { name: `1.png` },
},
}
expect(results.errors).toBeUndefined()
expect(results.data).toEqual(expected)
})
})
5 changes: 4 additions & 1 deletion packages/gatsby/src/schema/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,10 @@ const fileByPath = (source, args, context, info) => {

// Find the File node for this node (we assume the node is something
// like markdown which would be a child node of a File node).
const parentFileNode = context.nodeModel.findRootNodeAncestor(source)
const parentFileNode = context.nodeModel.findRootNodeAncestor(
source,
node => node.internal && node.internal.type === `File`
)

// Find the linked File node(s)
if (isArray) {
Expand Down

0 comments on commit 8031fcf

Please sign in to comment.