Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ plugins:[
consumer_secret: <secret>,
},
// Array of strings with fields you'd like to create nodes for...
fields: ['products']
fields: ['products'],
// Version of the woocommerce API to use
// OPTIONAL: defaults to 'wc/v1'
api_version: 'wc/v3',
// OPTIONAL: How many results to retrieve
per_page: 100
}
}
]
Expand All @@ -36,3 +41,7 @@ plugins:[
- Orders
- Reports
- Coupons

**Note**: If following the endpoint layout from the [WooCommerce REST API docs](https://woocommerce.github.io/woocommerce-rest-api-docs/?php#introduction), all fields that do not contain a wildcard *should* be supported.

For example, to get product categories: including 'products/categories' in fields will show up as allWcProductsCategories / wcProductsCategories
26 changes: 20 additions & 6 deletions gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const WooCommerceAPI = require('woocommerce-api');
const { processNode } = require('./helpers');
const { processNode, normaliseFieldName } = require('./helpers');

exports.sourceNodes = async (
{ boundActionCreators, createNodeId },
Expand All @@ -8,28 +8,42 @@ exports.sourceNodes = async (
const { createNode } = boundActionCreators;
delete configOptions.plugins;

const { api, https, api_keys, fields } = configOptions;
const { api, https, api_keys, fields, api_version = 'wc/v1', per_page } = configOptions;

// set up WooCommerce node api tool
const WooCommerce = new WooCommerceAPI({
url: `http${https?'s':''}://${api}`,
consumerKey: api_keys.consumer_key,
consumerSecret: api_keys.consumer_secret,
wpAPI: true,
version: 'wc/v1'
version: api_version
});

// Fetch Node and turn our response to JSON
const fetchNodes = async (fieldName) => {
const res = await WooCommerce.getAsync(fieldName);
return JSON.parse(res.toJSON().body);
const endpoint = per_page
? fieldName + `?per_page=${per_page}`
: fieldName;

const res = await WooCommerce.getAsync(endpoint);
const json = res.toJSON();
if(json.statusCode !== 200) {
console.warn(`
\n========== WARNING FOR FIELD ${fieldName} ==========\n`
);
console.warn(`The following error message was produced: ${json.body}`);
console.warn(`\n========== END WARNING ==========\n`);
return [];
}
return JSON.parse(json.body);
};

// Loop over each field set in configOptions and process/create nodes
async function fetchNodesAndCreate (array) {
for (const field of array) {
const nodes = await fetchNodes(field);
nodes.forEach(n=>createNode(processNode(createNodeId, n, field)));
const fieldName = normaliseFieldName(field);
nodes.forEach(n=>createNode(processNode(createNodeId, n, fieldName)));
}
}

Expand Down
15 changes: 14 additions & 1 deletion helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const processNode = (createNodeId, node, fieldName) => {

const nodeData = Object.assign({}, node, {
id: nodeId,
wordpress_id: node['id'],
parent: null,
children: [],
internal: {
Expand All @@ -21,7 +22,19 @@ const processNode = (createNodeId, node, fieldName) => {
return nodeData
};

module.exports = { processNode };
// Turn multi part endpoints into camelCase
// e.g. products/categories becomes productsCategories
const normaliseFieldName = (name) => {
const parts = name.split('/');
return parts.reduce((whole, partial) => {
if(whole === '') {
return whole.concat(partial);
}
return whole.concat(partial[0].toUpperCase() + partial.slice(1));
}, '')
}

module.exports = { processNode, normaliseFieldName };

// Helper Helpers
function capitalize(s){
Expand Down