Skip to content

Commit

Permalink
refactor gatsby node
Browse files Browse the repository at this point in the history
  • Loading branch information
justinwhall committed Jun 15, 2019
1 parent 8258d24 commit dcc61fb
Show file tree
Hide file tree
Showing 4 changed files with 2,201 additions and 1,852 deletions.
218 changes: 127 additions & 91 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,97 +1,133 @@
<!-- AUTO-GENERATED-CONTENT:START (STARTER) -->
<p align="center">
<a href="https://www.gatsbyjs.org">
<img alt="Gatsby" src="https://www.gatsbyjs.org/monogram.svg" width="60" />
</a>
</p>
<h1 align="center">
Gatsby's blog starter
</h1>

Kick off your project with this blog boilerplate. This starter ships with the main Gatsby configuration files you might need to get up and running blazing fast with the blazing fast app generator for React.

_Have another more specific idea? You may want to check out our vibrant collection of [official and community-created starters](https://www.gatsbyjs.org/docs/gatsby-starters/)._

## 🚀 Quick start

1. **Create a Gatsby site.**

Use the Gatsby CLI to create a new site, specifying the blog starter.

```sh
# create a new Gatsby site using the blog starter
gatsby new my-blog-starter https://github.com/gatsbyjs/gatsby-starter-blog
```

1. **Start developing.**

Navigate into your new site’s directory and start it up.

```sh
cd my-blog-starter/
gatsby develop
```

1. **Open the source code and start editing!**

Your site is now running at `http://localhost:8000`!

_Note: You'll also see a second link: _`http://localhost:8000/___graphql`_. This is a tool you can use to experiment with querying your data. Learn more about using this tool in the [Gatsby tutorial](https://www.gatsbyjs.org/tutorial/part-five/#introducing-graphiql)._
Open the `my-blog-starter` directory in your code editor of choice and edit `src/pages/index.js`. Save your changes and the browser will update in real time!
## 🧐 What's inside?

A quick look at the top-level files and directories you'll see in a Gatsby project.
.
├── node_modules
├── src
├── .gitignore
├── .prettierrc
├── gatsby-browser.js
├── gatsby-config.js
├── gatsby-node.js
├── gatsby-ssr.js
├── LICENSE
├── package-lock.json
├── package.json
└── README.md
1. **`/node_modules`**: This directory contains all of the modules of code that your project depends on (npm packages) are automatically installed.
2. **`/src`**: This directory will contain all of the code related to what you will see on the front-end of your site (what you see in the browser) such as your site header or a page template. `src` is a convention for “source code”.
3. **`.gitignore`**: This file tells git which files it should not track / not maintain a version history for.
4. **`.prettierrc`**: This is a configuration file for [Prettier](https://prettier.io/). Prettier is a tool to help keep the formatting of your code consistent.
5. **`gatsby-browser.js`**: This file is where Gatsby expects to find any usage of the [Gatsby browser APIs](https://www.gatsbyjs.org/docs/browser-apis/) (if any). These allow customization/extension of default Gatsby settings affecting the browser.
6. **`gatsby-config.js`**: This is the main configuration file for a Gatsby site. This is where you can specify information about your site (metadata) like the site title and description, which Gatsby plugins you’d like to include, etc. (Check out the [config docs](https://www.gatsbyjs.org/docs/gatsby-config/) for more detail).
7. **`gatsby-node.js`**: This file is where Gatsby expects to find any usage of the [Gatsby Node APIs](https://www.gatsbyjs.org/docs/node-apis/) (if any). These allow customization/extension of default Gatsby settings affecting pieces of the site build process.
8. **`gatsby-ssr.js`**: This file is where Gatsby expects to find any usage of the [Gatsby server-side rendering APIs](https://www.gatsbyjs.org/docs/ssr-apis/) (if any). These allow customization of default Gatsby settings affecting server-side rendering.
9. **`LICENSE`**: Gatsby is licensed under the MIT license.
10. **`package-lock.json`** (See `package.json` below, first). This is an automatically generated file based on the exact versions of your npm dependencies that were installed for your project. **(You won’t change this file directly).**
11. **`package.json`**: A manifest file for Node.js projects, which includes things like metadata (the project’s name, author, etc). This manifest is how npm knows which packages to install for your project.
12. **`README.md`**: A text file containing useful reference information about your project.
## 🎓 Learning Gatsby
Looking for more guidance? Full documentation for Gatsby lives [on the website](https://www.gatsbyjs.org/). Here are some places to start:
- **For most developers, we recommend starting with our [in-depth tutorial for creating a site with Gatsby](https://www.gatsbyjs.org/tutorial/).** It starts with zero assumptions about your level of ability and walks through every step of the process.
- **To dive straight into code samples, head [to our documentation](https://www.gatsbyjs.org/docs/).** In particular, check out the _Guides_, _API Reference_, and _Advanced Tutorials_ sections in the sidebar.
## 💫 Deploy
[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/gatsbyjs/gatsby-starter-blog)
<!-- AUTO-GENERATED-CONTENT:END -->
# Gatsby + Headless WordPress + Netlify Starter

A starter skeleton that leverages the WordPress API for [Gatsby](https://github.com/gatsbyjs/gatsby/). Support for Continuous integration with Netlify. Publishing posts call the Netlify build hook. Deploy to Netlify stage or production enviroment when updating a WordPress post or page.

## Dependencies

* [LittleBot Netlify](https://github.com/justinwhall/littlebot-netlify) installed and activated on the source WordPress installation.

#### This Project was forked from the default [Gatsby Starter](https://github.com/gatsbyjs/gatsby-starter-blog)


### [Production Demo](https://gatsby-wordpress-netlify-production.netlify.com/)
### [Stage Demo](https://gatsby-wordpress-netlify-stage.netlify.com/)

## Getting Started
1. Fork Gatsby WordPress Netlify
2. Clone your forked repository
3. `npm install --global gatsby-cli` (if you don't have Gatsby CLI installed)
4. In the root of your project yarn install
5. Open your `gatsby-config.js` file and change the baseUrl to your WordPress url
6. Run `yarn develop` -- _not_ `gatsby develop`

### Netlify
_Signup for a Netlify account if you don't already have one._

1. Create a new site
2. Select "GitHub" from "Continuous Deployment"
3. Search and select your repository
4. Click "show advanced"
5. Click "new variable"
6. Add a deploy key DEPLOY_ENV with a value of lbn_published_stage
7. Click "deploy site"
8. Under Settings > Build & Deploy click "add build hook"
9. Name something that signifies environment (stage or production)
10. (Optional) Click "site options" and then "change site name". Rename to something that signifies this is the environment (stage or production).
11. (Optional) Repeat the process above a second time to create a production environment. Change the DEPLOY_ENV to lbn_published_production Optionally rename accordingly.

### Install WordPress
Install WordPress on the server of your choice or use an existing site. I recommend a stripped down theme with no front end like this. For example, this site uses [https://gatsbynetlifydemo.justinwhall.com/](https://gatsbynetlifydemo.justinwhall.com/) for its data source. which is no more than a stripped down _s theme.

### Install LittleBot Netlify plugin (Optional. Can be used without this if you don't care about building on publish.)

1. Download or clone the [LittleBot Netlify plugin](https://github.com/justinwhall/littlebot-netlify) and install on your source WordPress site.
2. Find your build hooks on Netlify **Settings > Build & Deploy**
3. Add build hooks to your WordPress install under **WP Admin > Settings > LittleBot Netlify** 

### Publish!

Support for Gutenberg out of the box. If you are using the classic editor, the default "Publish" metabox has been replaced with:

<img src="https://gatsbynetliflydemo.justinwhall.com/wp-content/uploads/2018/06/Screenshot-2018-06-29-18.50.37_preview-300x180.png" alt="publish" />

If you update or publish a post with an environment checked, your post will be published to that environment. Likewise, if you update/publish with an environment unchecked, A post will be removed from that environment. For example, if you uncheck both environments and update, the post will be removed from both. If you publish/update with both environments checked, the post will be published to both.

### Example:

Using this starter requires configuring the gatsby-config.js file. You really only need to change BaseUrl, and hostingWPCOM if you're using WP.com rather than WP.org

```javascript
{
resolve: 'gatsby-source-wordpress',
options: {
// The base url to your WP site.
baseUrl: 'YOUR_WORDPRESS_URL',
// WP.com sites set to true, WP.org set to false
hostingWPCOM: false,
// The protocol. This can be http or https.
protocol: 'http',
// Use 'Advanced Custom Fields' Wordpress plugin
useACF: true,
auth: {},
// Set to true to debug endpoints on 'gatsby build'
verboseOutput: false
}
},
```

* Update GraphQL queries to match your WordPress Content. This is the query currently on the index page. You either need to add ACF's in your WordPress to match the query (in this case Project and Date), or you need to remove those aspects of the query. The featured_media isn't a problem -- it'll work even if you have posts without featured images.

```javascript
allWordpressPost {
edges {
node {
featured_media {
source_url
}
author {
name
avatar_urls {
wordpress_24
wordpress_48
wordpress_96
}
}
date
slug
title
modified
excerpt
id
acf {
project
date
}
categories {
name
}
tags {
name
}
content
}
}
}
```

* Finally, you'll probably want to update the SiteConfig to match your info, because right now it has mine. 🤠
* Suggestions:
* Use the Prism WP Plugin to pass code blocks down.
* If you give an ACF to a single post, you must give it to EVERY post, or GraphQL gets confused.

### Notes

[Ruben Harutyunyan](https://github.com/Vagr9K) did most of the hard work with [Gatsby Advanced Starter](https://github.com/Vagr9K/gatsby-advanced-starter).
The rest of the credit is due to [Gatsby](https://github.com/gatsbyjs/gatsby/).

WARNING: Make sure to edit `static/robots.txt` to include your domain for the sitemap!
68 changes: 13 additions & 55 deletions gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const DEPLOY_ENV = process.env.DEPLOY_ENV || 'lbn_published_production';

const DEPLOY_ENV = process.env.DEPLOY_ENV || 'lbn_published_production';

/**
* Generate node edges
Expand All @@ -9,7 +8,14 @@ const DEPLOY_ENV = process.env.DEPLOY_ENV || 'lbn_published_production';
exports.onCreateNode = ({ node, actions }) => {
const { createNodeField } = actions;

if (!Object.prototype.hasOwnProperty.call(node, 'meta')) {
/**
* If these don't exist, the LBN WordPress Plugin isn't installed – so build all posts.
*/
if (
!Object.prototype.hasOwnProperty.call(node, 'meta') ||
!Object.prototype.hasOwnProperty.call(node.meta, 'lbn_published_production')
) {
createNodeField({ node, name: 'deploy', value: true });
return;
}

Expand All @@ -25,60 +31,12 @@ exports.onCreateNode = ({ node, actions }) => {
};


exports.sourceNodes = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
# Define the featured_media type so we know it's in the schema
type wordpress__POST implements Node {
featured_media: featImg
}
type featImg implements Node {
source_url: String
}
`
createTypes(typeDefs)
}

exports.createResolvers = ({ createResolvers }) => {
const resolvers = {
wordpress__POST: {
featured_media: {
resolve: (source, args, context, info) => {

console.log(JSON.stringify(source._links, null, 4));
/**
* Check to see if we have a featured image. If not, set a default.
* We Could also set it to false if wanted to support logic like -> if (featured_image) { // do stuff }
*/
if (source._links && source._links.self.wp_featuredmedia) {
return info.originalResolver(source, args, context, info)
} else {
return info.originalResolver(
{
...source,
featured_media: {
source_url: "https://sendgrid.com/wp-content/uploads/2019/06/iStock-1011506076-2340x1000.jpg"
}
},
args,
context,
info
)
}
}
}
}
}
createResolvers(resolvers)
}


const createPosts = require('./gatsby/createPosts');
const createPages = require('./gatsby/createPages');
const createCategories = require('./gatsby/createCategories');

exports.createPages = async ({ actions, graphql }) => {
await createPosts({ actions, graphql })
await createPages({ actions, graphql })
await createCategories({ actions, graphql })
}
await createPosts({ actions, graphql });
await createPages({ actions, graphql });
await createCategories({ actions, graphql });
}
15 changes: 14 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,20 @@
"typography-theme-wordpress-2016": "^0.16.19"
},
"devDependencies": {
"prettier": "^1.18.0"
"prettier": "^1.18.0",
"cli-glob": "^0.1.0",
"eslint": "^3.19.0",
"eslint-config-airbnb": "^15.0.2",
"eslint-config-prettier": "^2.9.0",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^5.1.1",
"eslint-plugin-react": "^7.5.1",
"gh-pages": "^1.1.0",
"remark-cli": "^4.0.0",
"remark-preset-lint-recommended": "^3.0.1",
"stylefmt": "^6.0.0",
"stylelint": "^8.4.0",
"stylelint-config-standard": "^18.0.0"
},
"homepage": "https://github.com/gatsbyjs/gatsby-starter-blog#readme",
"keywords": [
Expand Down
Loading

0 comments on commit dcc61fb

Please sign in to comment.