Skip to content

Commit

Permalink
Implemented pluggable normalisers
Browse files Browse the repository at this point in the history
  • Loading branch information
David Hewitt committed Jan 30, 2018
1 parent 85f654d commit 9caafa7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 15 deletions.
13 changes: 10 additions & 3 deletions packages/gatsby-source-wordpress/src/gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const fetch = require(`./fetch`)
const normalize = require(`./normalize`)
const Normalizer = require(`./normalizer`)
const _ = require(`lodash`)

const typePrefix = `wordpress__`
const refactoredEntityTypes = {
Expand Down Expand Up @@ -77,13 +78,19 @@ exports.sourceNodes = async (
.set(normalize.searchReplaceContentUrls, 130)

for (let i = 0; i < plugins.length; i++) {
const requiredPlugin = require(plugins[i].resolve)
normalizer = requiredPlugin.normalize(normalizer)
var requiredPlugin = require(plugins[i].resolve)

if (_.isFunction(requiredPlugin.normalize)) {
var pluginNormalizer = requiredPlugin.normalize(normalizer)
if (pluginNormalizer instanceof Normalizer) {
normalizer = pluginNormalizer
}
}

}

entities = await normalizer.normalize()

// creates nodes for each entry
normalize.createNodesFromEntities({ entities, createNode })

return
Expand Down
51 changes: 39 additions & 12 deletions packages/gatsby-source-wordpress/src/normalizer.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,65 @@
const _ = require(`lodash`)

class Normalizer {

/**
* Normalizer Constructor
*
* @param {Array} entitys
* @param {Object} args
* @return {Object} this
*/
constructor(entitys, args) {
this.entitys = entitys
this.args = args
this.normalizers = []
this.queue = []
}

/**
* Set Normalizers
*
* @param {Function} normalizer
* @param {null|Number} priority
* @return {Object}
*/
set(normalizer, priority = null) {
// if the priority is null push last
this.normalizers.push({
let property = priority === null ? `queue` : `normalizers`

this[property].push({
normalizer,
priority,
})

return this
}

/**
* Normalize the entities
*
* @return {Array}
*/
async normalize() {
let ordered = this.normalizers.sort((a, b) => a.priority - b.priority)

for (let i = 0; i < ordered.length; i++) {
var normalizedEntities = await ordered[i].normalizer(this.entitys, this.args)

if (typeof normalizedEntities !== `object`) {
continue
}

this.entitys = normalizedEntities
var normalizers = this.getNormalizers()
for (let i = 0; i < normalizers.length; i++) {
this.entitys = await normalizers[i].normalizer(this.entitys, this.args)
}

return this.entitys
}

/**
* Concat the queue and prioritised normalizers
*
* @return {Array}
*/
getNormalizers() {
return _.concat(
this.normalizers.sort((a, b) => a.priority - b.priority),
this.queue
)
}

}

module.exports = Normalizer

0 comments on commit 9caafa7

Please sign in to comment.