Skip to content

Commit

Permalink
[1.0] Make nodes fully immutable by adding API for allowing plugins t…
Browse files Browse the repository at this point in the history
…o add fields (#1035)

* remove updateNode action creator, rename 'pluginName' to 'pluginOwner', and add check that only original node creator is updating a node

* Add top-level field to nodes 'pluginFields'

* Replace 'updateNode' action creator with 'addChildNodeToParentNode' and 'addFieldToNode'

* Add test for nodes being created with field 'pluginFields'

* Use stripIndent so multiline strings look nicer in code

* Rename addChildNodeToParentNode to addNodeToParent

* Update transformer tests

* Fixed bit of code that didn't get updated for node structure refactor

* Simplify error message

* Check if there's actually results so avoiding access error

* Test nodes often don't have internal set

* Rename 'pluginFields' to 'fields'

* Rename other fields with 'plugin' in them

* Update migration guide with changes

* Update gatsbygram example code to wrap graphql call in resolve

* Update snapshot
  • Loading branch information
KyleAMathews committed May 26, 2017
1 parent 4784b06 commit 55845c9
Show file tree
Hide file tree
Showing 33 changed files with 777 additions and 326 deletions.
78 changes: 40 additions & 38 deletions docs/blog/gatsbygram-case-study/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,18 +164,18 @@ the site's [`gatsby-node.js`
file](https://github.com/gatsbyjs/gatsby/blob/1.0/examples/gatsbygram/gatsby-node.js):

```javascript
const _ = require("lodash")
const Promise = require("bluebird")
const path = require("path")
const slug = require("slug")
const slash = require("slash")
const _ = require(`lodash`)
const Promise = require(`bluebird`)
const path = require(`path`)
const slug = require(`slug`)
const slash = require(`slash`)

// Implement the Gatsby API “createPages”. This is
// called after the Gatsby bootstrap is finished so you have
// access to any information necessary to programatically
// create pages.
exports.createPages = ({ graphql, actionCreators }) => {
const { upsertPage } = actionCreators
exports.createPages = ({ graphql, boundActionCreators }) => {
const { upsertPage } = boundActionCreators

return new Promise((resolve, reject) => {
// The “graphql” function allows us to run arbitrary
Expand All @@ -184,14 +184,15 @@ exports.createPages = ({ graphql, actionCreators }) => {
// from static data that you can run queries against.
//
// Post is a data node type derived from data/posts.json
// which is created when scrapping Instagram. “allPosts
// which is created when scrapping Instagram. “allPostsJson
// is a "connection" (a GraphQL convention for accessing
// a list of nodes) gives us an easy way to query all
// Post nodes.
graphql(
`
resolve(
graphql(
`
{
allPosts(limit: 1000) {
allPostsJson(limit: 1000) {
edges {
node {
id
Expand All @@ -200,36 +201,37 @@ exports.createPages = ({ graphql, actionCreators }) => {
}
}
`
).then(result => {
if (result.errors) {
console.log(result.errors)
reject(result.errors)
}
).then(result => {
if (result.errors) {
reject(new Error(result.errors))
}

// Create image post pages.
const postTemplate = path.resolve(`templates/post-page.js`)
// We want to create a detailed page for each
// Instagram post. Since the scrapped Instagram data
// already includes an ID field, we just use that for
// each page's path.
_.each(result.data.allPosts.edges, edge => {
// Gatsby uses Redux to manage its internal state.
// Plugins and sites can use functions like "upsertPage"
// to interact with Gatsby.
upsertPage({
// Each page is required to have a `path` as well
// as a template component. The `context` is
// optional but is often necessary so the template
// can query data specific to each page.
path: slug(edge.node.id),
component: slash(postTemplate),
context: {
id: edge.node.id,
},
// Create image post pages.
const postTemplate = path.resolve(`src/templates/post-page.js`)
// We want to create a detailed page for each
// Instagram post. Since the scrapped Instagram data
// already includes an ID field, we just use that for
// each page's path.
_.each(result.data.allPostsJson.edges, edge => {
// Gatsby uses Redux to manage its internal state.
// Plugins and sites can use functions like "upsertPage"
// to interact with Gatsby.
upsertPage({
// Each page is required to have a `path` as well
// as a template component. The `context` is
// optional but is often necessary so the template
// can query data specific to each page.
path: `/${slug(edge.node.id)}/`,
component: slash(postTemplate),
context: {
id: edge.node.id,
},
})
})

return
})
resolve()
})
)
})
}
```
Expand Down
20 changes: 10 additions & 10 deletions docs/docs/migrating-from-v0-to-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,15 +120,14 @@ module.exports = {
It's handy to store the pathname of "slug" for each markdown page with the
markdown data. This let's you easily query the slug from multiple places.

Here's how you do that (note, these APIs will be changing slightly soon but the
logic of your code will remain the same).
Here's how you do that.

```javascript
// In your gatsby-node.js
const path = require('path')

exports.onNodeCreate = ({ node, boundActionCreators, getNode }) => {
const { updateNode } = boundActionCreators
const { addFieldToNode } = boundActionCreators
let slug
if (node.internal.type === `MarkdownRemark`) {
const fileNode = getNode(node.parent)
Expand All @@ -141,9 +140,8 @@ exports.onNodeCreate = ({ node, boundActionCreators, getNode }) => {
slug = `/${parsedFilePath.dir}/`
}

// Set the slug on the node and save the change.
node.slug = slug
updateNode(node)
// Add slug as a field on the node.
addFieldToNode({ node: node.id, fieldName: `slug`, fieldValue: slug })
}
}
```
Expand All @@ -166,7 +164,9 @@ exports.createPages = ({ graphql, boundActionCreators }) => {
allMarkdownRemark {
edges {
node {
slug
fields {
slug
}
}
}
}
Expand All @@ -181,10 +181,10 @@ exports.createPages = ({ graphql, boundActionCreators }) => {
// Create blog posts pages.
result.data.allMarkdownRemark.edges.forEach(edge => {
upsertPage({
path: edge.node.slug, // required
path: edge.node.fields.slug, // required
component: blogPost,
context: {
slug: edge.node.slug,
slug: edge.node.fields.slug,
},
})
})
Expand Down Expand Up @@ -227,7 +227,7 @@ export default BlogPostTemplate

export const pageQuery = graphql`
query BlogPostBySlug($slug: String!) {
markdownRemark(slug: { eq: $slug }) {
markdownRemark(fields: { slug: { eq: $slug }}) {
html
frontmatter {
title
Expand Down
9 changes: 8 additions & 1 deletion docs/docs/node-interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,18 @@ The basic node data structure is as follows:
id: String,
children: Array[String],
parent: String,
// Reserved for plugins who wish to extend other nodes.
fields: Object,
internal: {
contentDigest: String,
mediaType: String,
// A globally unique node type choosen by the plugin owner.
type: String,
pluginName: String,
// The plugin which created this node.
owner: String,
// Stores which plugins created which fields.
fieldOwners: Object,
// Raw content for this node.
content: String,
}
...other node type specific fields
Expand Down
60 changes: 31 additions & 29 deletions examples/gatsbygram/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ exports.createPages = ({ graphql, boundActionCreators }) => {
// is a "connection" (a GraphQL convention for accessing
// a list of nodes) gives us an easy way to query all
// Post nodes.
graphql(
`
resolve(
graphql(
`
{
allPostsJson(limit: 1000) {
edges {
Expand All @@ -34,35 +35,36 @@ exports.createPages = ({ graphql, boundActionCreators }) => {
}
}
`
).then(result => {
if (result.errors) {
reject(new Error(result.errors))
}
).then(result => {
if (result.errors) {
reject(new Error(result.errors))
}

// Create image post pages.
const postTemplate = path.resolve(`src/templates/post-page.js`)
// We want to create a detailed page for each
// Instagram post. Since the scrapped Instagram data
// already includes an ID field, we just use that for
// each page's path.
_.each(result.data.allPostsJson.edges, edge => {
// Gatsby uses Redux to manage its internal state.
// Plugins and sites can use functions like "upsertPage"
// to interact with Gatsby.
upsertPage({
// Each page is required to have a `path` as well
// as a template component. The `context` is
// optional but is often necessary so the template
// can query data specific to each page.
path: `/${slug(edge.node.id)}/`,
component: slash(postTemplate),
context: {
id: edge.node.id,
},
// Create image post pages.
const postTemplate = path.resolve(`src/templates/post-page.js`)
// We want to create a detailed page for each
// Instagram post. Since the scrapped Instagram data
// already includes an ID field, we just use that for
// each page's path.
_.each(result.data.allPostsJson.edges, edge => {
// Gatsby uses Redux to manage its internal state.
// Plugins and sites can use functions like "upsertPage"
// to interact with Gatsby.
upsertPage({
// Each page is required to have a `path` as well
// as a template component. The `context` is
// optional but is often necessary so the template
// can query data specific to each page.
path: `/${slug(edge.node.id)}/`,
component: slash(postTemplate),
context: {
id: edge.node.id,
},
})
})
})

resolve()
})
return
})
)
})
}
3 changes: 1 addition & 2 deletions packages/gatsby-transformer-json/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
"author": "Kyle Mathews <mathews.kyle@gmail.com>",
"license": "MIT",
"dependencies": {
"bluebird": "^3.5.0",
"unist-util-select": "^1.5.0"
"bluebird": "^3.5.0"
},
"devDependencies": {
"babel-cli": "^6.24.1"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,58 @@ exports[`Process JSON nodes correctly correctly creates nodes from JSON which is
Array [
Array [
Object {
"children": Array [
"foo",
"whatever [1] >>> JSON",
],
"content": "[{\\"id\\":\\"foo\\",\\"blue\\":true,\\"funny\\":\\"yup\\"},{\\"blue\\":false,\\"funny\\":\\"nope\\"}]",
"id": "whatever",
"internal": Object {
"contentDigest": "whatever",
"mediaType": "application/json",
"name": "test",
"child": Object {
"blue": true,
"children": Array [],
"funny": "yup",
"id": "foo",
"internal": Object {
"content": "{\\"id\\":\\"foo\\",\\"blue\\":true,\\"funny\\":\\"yup\\"}",
"contentDigest": "8838e569ae02d98806532310fb2a577a",
"mediaType": "application/json",
"type": "UndefinedJson",
},
"parent": "whatever",
},
"parent": Object {
"children": Array [],
"content": "[{\\"id\\":\\"foo\\",\\"blue\\":true,\\"funny\\":\\"yup\\"},{\\"blue\\":false,\\"funny\\":\\"nope\\"}]",
"id": "whatever",
"internal": Object {
"contentDigest": "whatever",
"mediaType": "application/json",
"name": "test",
},
"parent": "SOURCE",
},
},
],
Array [
Object {
"child": Object {
"blue": false,
"children": Array [],
"funny": "nope",
"id": "whatever [1] >>> JSON",
"internal": Object {
"content": "{\\"blue\\":false,\\"funny\\":\\"nope\\"}",
"contentDigest": "f624311d932d73dcd416d2a8bea2b67d",
"mediaType": "application/json",
"type": "UndefinedJson",
},
"parent": "whatever",
},
"parent": Object {
"children": Array [],
"content": "[{\\"id\\":\\"foo\\",\\"blue\\":true,\\"funny\\":\\"yup\\"},{\\"blue\\":false,\\"funny\\":\\"nope\\"}]",
"id": "whatever",
"internal": Object {
"contentDigest": "whatever",
"mediaType": "application/json",
"name": "test",
},
"parent": "SOURCE",
},
"parent": "SOURCE",
},
],
]
Expand Down
16 changes: 8 additions & 8 deletions packages/gatsby-transformer-json/src/__tests__/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,18 @@ describe(`Process JSON nodes correctly`, () => {
node.content = JSON.stringify(data)

const createNode = jest.fn()
const updateNode = jest.fn()
const boundActionCreators = { createNode, updateNode }
const addNodeToParent = jest.fn()
const boundActionCreators = { createNode, addNodeToParent }

await onNodeCreate({
node,
loadNodeContent,
boundActionCreators,
}).then(() => {
expect(createNode.mock.calls).toMatchSnapshot()
expect(updateNode.mock.calls).toMatchSnapshot()
expect(addNodeToParent.mock.calls).toMatchSnapshot()
expect(createNode).toHaveBeenCalledTimes(2)
expect(updateNode).toHaveBeenCalledTimes(1)
expect(addNodeToParent).toHaveBeenCalledTimes(2)
})
})

Expand All @@ -49,8 +49,8 @@ describe(`Process JSON nodes correctly`, () => {
node.content = JSON.stringify(data)

const createNode = jest.fn()
const updateNode = jest.fn()
const boundActionCreators = { createNode, updateNode }
const addNodeToParent = jest.fn()
const boundActionCreators = { createNode, addNodeToParent }

await onNodeCreate({
node,
Expand All @@ -71,8 +71,8 @@ describe(`Process JSON nodes correctly`, () => {
node.content = JSON.stringify(data)

const createNode = jest.fn()
const updateNode = jest.fn()
const boundActionCreators = { createNode, updateNode }
const addNodeToParent = jest.fn()
const boundActionCreators = { createNode, addNodeToParent }

await onNodeCreate({
node,
Expand Down
Loading

0 comments on commit 55845c9

Please sign in to comment.