Skip to content

Integrating Contentful into BreakOut

tomkellog edited this page Jan 24, 2017 · 1 revision

Fetching content from Contentful and using it to render static pages within BreakOut can be achieved in a few simple steps:

1. Connecting to our Contentful space

The Contentful client that is used to obtain data must be imported and can be set up as such:

const contentful = require('contentful');

const contentfulClient = contentful.createClient({
  space: space,
  accessToken: accessToken
});

We must specify our Contentful space id in space and provide our access token in accessToken.

2.Fetching the right content

In order to obtain all entries of a specific content type and in a specific language from Contentful we simply call

getFieldsForContentType( contenttype_id, language)

where contenttype_id is a string holding the Contentful id for the type of content we are looking for and language is a string with the preferred browser language stored in the request and obtained with req.acceptsLanguages()[0].

getFieldsForContentType is responsible for extracting the fields field of the object returned by the Contentful client and is implemented as

function getFieldsForContentType(contentType, locale) {
  return contentfulClient.getEntries({
    content_type: contentType,
    locale: locale,
  }).then(res => res.items.map(item => item.fields));
}

3. Waiting for the content

To prevent our code from using content that has not yet been fully fetched, we use Promises within a generator function, thus effectively waiting for the Contentful client before attempting to use the fetched content.

    const data = yield Promise.all([
      getFieldsForContentType('content_type_1', req.contentfulLocale),
      getFieldsForContentType('content_type_1', req.contentfulLocale)
    ]);

data then stores the content.