Skip to content

Commit

Permalink
Merge pull request #62 from storyblok/feature/add-gatsby-image-update
Browse files Browse the repository at this point in the history
feat: add support for dynamic  gatsby image
  • Loading branch information
lisilinhart authored Dec 13, 2021
2 parents c18b6b4 + 56a15f5 commit 87bb453
Show file tree
Hide file tree
Showing 7 changed files with 10,762 additions and 10,734 deletions.
14 changes: 14 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = {
env: {
node: true,
commonjs: true,
es2021: true,
},
extends: 'eslint:recommended',
ignorePatterns: ['tests/*'],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
rules: {},
};
7 changes: 7 additions & 0 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
endOfLine: 'lf',
semi: true,
singleQuote: true,
tabWidth: 2,
printWidth: 100,
};
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,49 @@ module.exports = {
options: {
accessToken: 'YOUR_TOKEN',
version: 'draft',
localAssets: true, // Optional parameter to download the images to use with Gatsby Image Plugin
languages: ['de', 'at'] // Optional parameter. Omission will retrieve all languages by default.
}
}
]
}
```

### With Gatsby's image

You need to set the `localAssets` option to `true`. Here is an example of the usage:

```
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
function BlogPost({ data }) {
const image = getImage(data.file)
return (
<section>
<h2>{data.blogPost.title}</h2>
<GatsbyImage image={image} />
</section>
)
}
export const pageQuery = graphql`
query {
file(name: {eq: "demo"}) {
absolutePath
url
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
`
```

### With Gatsby's createPages

For more info regarding `createPages` see the Gatsby docs: [docs/reference/config-files/gatsby-node/#createPages](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/#createPages)
Expand Down
129 changes: 89 additions & 40 deletions gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,96 +1,145 @@
const StoryblokClient = require('storyblok-js-client')
const Sync = require('./src/sync')
const getStoryParams = require('./src/getStoryParams')
const stringify = require('json-stringify-safe')
const StoryblokClient = require('storyblok-js-client');
const Sync = require('./src/sync');
const getStoryParams = require('./src/getStoryParams');
const stringify = require('json-stringify-safe');
const { createRemoteFileNode } = require(`gatsby-source-filesystem`);

exports.sourceNodes = async function({ actions }, options) {
const { createNode, setPluginStatus } = actions
const client = new StoryblokClient(options)
exports.sourceNodes = async function ({ actions }, options) {
const { createNode, setPluginStatus } = actions;
const client = new StoryblokClient(options);

Sync.init({
createNode,
setPluginStatus,
client
})
client,
});

const space = await Sync.getSpace()
const languages = options.languages ? options.languages : space.language_codes
languages.push('')
const space = await Sync.getSpace();
const languages = options.languages ? options.languages : space.language_codes;
languages.push('');

for (const language of languages) {
await Sync.getAll('stories', {
node: 'StoryblokEntry',
params: getStoryParams(language, options),
process: (item) => {
for (var prop in item.content) {
// eslint-disable-next-line no-prototype-builtins
if (!item.content.hasOwnProperty(prop) || ['_editable', '_uid'].indexOf(prop) > -1) {
continue;
}
const objectType = Object.prototype.toString.call(item.content[prop])
.replace('[object ', '')
.replace(']', '')
.toLowerCase()
const objectType = Object.prototype.toString
.call(item.content[prop])
.replace('[object ', '')
.replace(']', '')
.toLowerCase();

if (['number', 'boolean', 'string'].indexOf(objectType) === -1) {
continue;
}

const type = prop == 'component' ? '' : ('_' + objectType)
const type = prop == 'component' ? '' : '_' + objectType;

item['field_' + prop + type] = item.content[prop]
item['field_' + prop + type] = item.content[prop];
}
item.content = stringify(item.content)
}
})

item.content = stringify(item.content);
},
});
}

await Sync.getAll('tags', {
node: 'StoryblokTag',
params: getStoryParams('', options),
process: (item) => {
item.id = item.name
}
})
item.id = item.name;
},
});

if (options.includeLinks === true) {
await Sync.getAll('links', {
node: 'StoryblokLink',
params: getStoryParams('', options)
})
params: getStoryParams('', options),
});
}

const datasources = await Sync.getAll('datasources', {
node: 'StoryblokDatasource'
})
node: 'StoryblokDatasource',
});

for (const datasource of datasources) {
const datasourceSlug = datasource.slug
const datasourceSlug = datasource.slug;

await Sync.getAll('datasource_entries', {
node: 'StoryblokDatasourceEntry',
params: {
datasource: datasourceSlug
datasource: datasourceSlug,
},
process: (item) => {
item.data_source_dimension = null
item.data_source = datasourceSlug
}
})
item.data_source_dimension = null;
item.data_source = datasourceSlug;
},
});

const datasourceDimensions = datasource.dimensions || []
const datasourceDimensions = datasource.dimensions || [];

for (const dimension of datasourceDimensions) {
await Sync.getAll('datasource_entries', {
node: 'StoryblokDatasourceEntry',
params: {
datasource: datasourceSlug,
dimension: dimension.entry_value
dimension: dimension.entry_value,
},
process: (item) => {
item.data_source_dimension = dimension.entry_value
item.data_source = datasourceSlug
item.data_source_dimension = dimension.entry_value;
item.data_source = datasourceSlug;
},
});
}
}
};

exports.onCreateNode = async (
{ node, actions: { createNode }, createNodeId, getCache, cache },
options
) => {
if (!options.localAssets) {
return;
}

if (node.internal.type === 'StoryblokEntry') {
const assetRegex = /(https:\/\/a\.storyblok\.com.+?(?:\.)(\w)*)/g;
let imagePaths = node.content.match(assetRegex);
if (imagePaths?.length) {
imagePaths.forEach(async (imagePath) => {
let fileNodeID;

const mediaDataCacheKey = `sb-${imagePath}`;
const cacheMediaData = await getCache(mediaDataCacheKey);
const isCached = cacheMediaData && node.cv === cacheMediaData.updatedAt;

if (isCached) {
fileNodeID = cacheMediaData.fileNodeID;
}

if (!fileNodeID && imagePath) {
const fileNode = await createRemoteFileNode({
url: imagePath,
parentNodeId: node.id,
createNode,
createNodeId,
getCache,
});

if (fileNode.id) {
fileNodeID = fileNode.id;
await cache.set(mediaDataCacheKey, {
fileNodeID,
updatedAt: node.cv,
});
}
}
})
});
}
}
}
};
Loading

0 comments on commit 87bb453

Please sign in to comment.