How to handle Contentful content data in Gatsby - contentful

I'm interested in using Gatsby to build a Netlify static site using content from Contentful
Netlify has this nice gettting started Gatsby guide:
​​https://www.netlify.com/blog/2016/02/24/a-step-by-step-guide-gatsby-on-netlify
But I'm a bit unsure of how to bring Contentful into the mix. Do I need to write scripts to convert my Contentful content into Gatsby 'markdown'?
Any ideas, ideas, links appreciated!

Since this question was posted, an official Contentful plugin's been added to Gatsby's collection (official as in created by Gatsby team, not Contentful): https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-source-contentful
An example site's src code is here: https://github.com/gatsbyjs/gatsby/tree/master/examples/using-contentful
The plugin processes markdown via gatsby-transformer-remark and produces the resultant HTML, which you can access via Gatsby's GraphQL server w/ a query like this one from the example proj:
contentfulProduct(id: { eq: $id }) {
productName {
productName
}
productDescription {
childMarkdownRemark {
html
}
}
price
}
You can use the plugin to connect both to the Content API (for published assets/content) and/or the Preview API (for both published and draft content/assets).
We use NODE_ENV to pull from the Preview API in dev and the Content API in production.

Here's the script I am using to pull down data from Contentful:
https://gist.github.com/ivanoats/e79ebbd711831be2536d1650890055c4
I run this via an npm run script before gatsby build.
I would love to work on a plugin or get ideas on better architecture for this process.
I wrote a post on this architecture in more detail on the Aerobatic blog

Right now the best option is to write a script which syncs content from Contentful to your Gatsby site's pages directory.
There's plans however for adding support within Gatsby to make this happen semi-automatically. Early days still here! See this issue for more https://github.com/gatsbyjs/gatsby/issues/324

Related

Contentful Content Migration API try/catch on field creation?

We are trying to setup a workflow for delivering content model changes to our other environments (stage & prod).
Right now, our approach is this:
Create a new contentful field as a migration script using Contentful CLI.
Run script in local dev to make sure the result is as desired using contentful space migration migrations/2023-01-12-add-field.ts
Add script to GIT in folder migrations/[date]-[description].js
When release to prod, run all scripts in the migrations folder, in order, as part of the build process.
When folder contains "too many" scripts, and we are certain all changes are applied to all envs, manually remove the scripts from GIT and start over in an empty folder.
Where it fails
But, between point 4 & 5 there will be cases where a script has already been run in an earlier release, and that throws an error:
I would like the scripts to continue more gracefully without throwing an error, but I cant find support for it in the space migration docs. I have tried wrapping the code in try/catch without any luck.
Contentful recommends using the Content Migration API in favour for Content Management API since it is faster. I guess we could use the Content Management API, but at the same time we want to use "best practise".
Are we missing something here?
I would like to do something like:
module.exports = function (migration) {
// Create a new category field in the blog post content type.
const blogPost = migration.editContentType('blogPost')
if (blogPost.fieldExists('testField')) {
console.log('Field already exists')
} else {
blogPost.createField('testField').name('Test field').type('Symbol')
}
}

Gatsby Failed Build - error "window" is not available during server side rendering

I have been trying to build my gatsby (react) site recently using an external package.
The link to this package is "https://github.com/transitive-bullshit/react-particle-animation".
As I only have the option to change the props from the components detail, I cannot read/write the package file where it all gets together in the end as it is not included in the public folder of 'gatsby-build'.
What I have tried:
Editing the package file locally, which worked only on my machine but when I push it to netlify, which just receives the public folder and the corresponding package.json files and not the 'node-modules folder', I cannot make netlify read the file that I myself changed, as it requests it directly from the github page.
As a solution I found from a comment to this question, we can use the "Patch-Package" to save our fixes to the node module and then use it wherever we want.
This actually worked for me!
To explain how I fixed it: (As most of it is already written in the "Patch Package DOCS), so mentioning the main points:
I first made changes to my local package files that were giving the error.(For me they were in my node_modules folder)
Then I used the Patch Package Documentation to guide my self through the rest.
It worked after I pushed my changes to github such that now, Patch Package always gives me my edited version of the node_module.
When dealing with third-party modules that use window in Gatsby you need to add a null loader to its own webpack configuration to avoid the transpilation during the SSR (Server-Side Rendering). This is because gatsby develop occurs in the browser (where there is a window) while gatsby build occurs in the Node server where obviously there isn't a window or other global objects (because they are not even defined yet).
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /react-particle-animation/,
use: loaders.null(),
},
],
},
})
}
}
Keep in mind that the test value is a regular expression that will match a folder under node_modules so, ensure that the /react-particle-animation/ is the right name.
Using a patch-package may work but keep in mind that you are adding an extra package, another bundled file that could potentially affect the performance of the site. The proposed snippet is a built-in solution that is fired when you build your application.

How to change Netlify CMS for Strapi CMS?

I'm new to this frontend world, I have some knowledge on React and GraphQL and that's why I've decided to try and implement a test blog with Gatsby, as it seems pretty popular and easy to use.
I also wanted to get my hands into Material UI so I'm using this Gatsby starter : https://www.gatsbyjs.org/starters/Vagr9K/gatsby-material-starter
This starter seems to have included the integration with Netlify CMS, so I wanted to change that and start using Strapi CMS, so I can have the content there.
Any idea on how to do this?
There's a lot of stuff in your question, I'll try to answer it step by step if not, please let me know if you need more details of how to create pages, etc and I will update my answer to add more details if needed.
If you want to change your source from Netlify to Strapi you need to set it up in your gatsby-config.js, replacing gatsby-plugin-netlify-cms plugin for something like that:
{
resolve: `gatsby-source-strapi`,
options: {
apiURL: `http://localhost:1337`,
queryLimit: 1000, // Default to 100
contentTypes: [`article`, `user`],
//If using single types place them in this array.
singleTypes: [`home-page`, `contact`],
// Possibility to login with a strapi user, when content types are not publically available (optional).
loginData: {
identifier: "",
password: "",
},
},
},
Note that you'll have to install your desired plugins and remove the unnecessary in order to reduce the bundle package and improve performance when using starters.
The next step is to create pages from your source CMS (articles, posts, pages, etc) using GraphQL. Maybe this blog helps you. But as a short summary, you need to create queries in your gatsby-node.js to retrieve data from Strapi CMS and create pages using Gatsby's API.
The idea is the same as from your starters, however, instead of using gatsby-source-filesystem and using allMarkdownRemark in your page creation, you will use the object provided by Strapi CMS. You can check the queries and the available objects using gatsby develop and entering to localhost:8000/___graphql.
Keep in mind that you will always query static data (i.e: pre-downloaded data) from your multiple sources so when you run the develop command, the data is downloaded and accessible via GraphQL.
You can check for further information in its starter repository.

How Do I Update the Swagger UI Documentation in JHipster?

In my JHipster app, I have manually updated the OpenAPI spec file (api.yml), following official instructions for API-first development.
However, the documentation (generated via Springfox) does not update, and still lists the endpoints described in the original (default) content of the api.yml.
As per Springfox's documentation,
All content is served from a webjar convention, relative url taking the following form: webjars/springfox-swagger-ui/2.9.2/swagger-ui.html
But there's no word about how to update that. Any ideas/clues welcome.
Thanks!

Drag 'n' Drop files to a Chrome Package App?

Has anyone successfully implemented drag and drop with files from desktop to the app?
I've tried just putting this drag 'n' drop example into the index file but I just get this error:
Can't open same-window link to "file:///C:/Users....whatever"; try target="_blank".
Please share your stories, what you've tried and if you have succeed :)
Some resources to help you:
New Chrome Packaged Apps codelab that we've been working on covers drag-and-drop in both AngularJS and pure JavaScript.
AngularJS drag-and-drop: https://github.com/GoogleChrome/chrome-app-codelab/tree/master/lab5_data/angularjs/2_drop_files
JavaScript drag-and-drop: https://github.com/GoogleChrome/chrome-app-codelab/tree/master/lab5_data/javascript/2_drop_files
There's an early version of docs too for AngularJS drag-and-drop for Chrome at developer.chrome.com/trunk/apps/app_codelab5_data.html#handle_drag_and_dropped_files_and_urls
We're working on the docs to cover both samples though.
I have done this a while ago and it worked.
The problem you've got is that you are creating a file url, then trying to navigate to the url. The navigation is failing, not the read. It's failing due to CSP, and you probably won't be able to override that with a different CSP due to security restrictions we've placed on allowable CSPs.
But, you should be able to just read the file and use the content. You need to change that sample code to use ReadAsText or ReadAsArrayBuffer instead of readAsDataURL. Look here for more details.
Please let us know how you get on!
Just listening for drop won't work. You will have to prevent the default functionality of dragover.
document.body.addEventListener('dragover', function(e) {
e.preventDefault();
}
document.body.addEventListener('drop', function(e) {
alert('it works!')
}

Resources