• This repository has been archived on 25/Jun/2021
  • Stars
    star
    185
  • Rank 207,452 (Top 5 %)
  • Language
    JavaScript
  • Created over 7 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate a GraphQL schema out of your Contentful space

cf-graphql

travis build status npm version npm downloads deps status dev deps status codecov coverage

cf-graphql is a library that allows you to query your data stored in Contentful with GraphQL. A schema and value resolvers are automatically generated out of an existing space.

Generated artifacts can be used with any node-based GraphQL server. The outcome of the project's main function call is an instance of the GraphQLSchema class.

Table of contents

Disclaimers

Please note that cf-graphql library is released as an experiment:

  • we might introduce breaking changes into programmatic interfaces and space querying approach before v1.0 is released
  • there’s no magic bullet: complex GraphQL queries can result in a large number of CDA calls, which will be counted against your quota
  • we might discontinue development of the library and stop maintaining it

First steps

If you just want to see how it works, please follow the Demo section. You can deploy the demo with your own credentials so it queries your own data.

In general cf-graphql is a library and it can be used as a part of your project. If you want to get your hands dirty coding, follow the Programmatic usage section.

Demo

We host an online demo for you. You can query Contentful's "Blog" space template there. This how its graph looks like:

Demo space graph

Run it locally

This repository contains a demo project. The demo comes with a web server (with CORS enabled) providing the GraphQL, an in-browser IDE (GraphiQL) and a React Frontend application using this endpoint.

To run it, clone the repository, install dependencies and start a server:

git clone [email protected]:contentful-labs/cf-graphql.git
cd cf-graphql/demo
# optionally change your node version with nvm, anything 6+ should work just fine
# we prefer node v6 matching the current AWS Lambda environment
nvm use
npm install
npm start

Use http://localhost:4000/graphql/ to query the data from within your application and navigate to http://localhost:4000 to use the IDE (GraphiQL) for test-querying. Please refer to the Querying section for more details.

If you also want to see how to integrate GraphQL in a React technology stack the demo project also contains an application based on the Apollo framework. To check it out use http://localhost:4000/client/.

To use your own Contentful space with the demo, you have to provide:

  • space ID
  • CDA token
  • CMA token

Please refer the "Authentication" section of Contentful's documentation.

You can provide listed values with env variables:

SPACE_ID=some-space-id CDA_TOKEN=its-cda-token CMA_TOKEN=your-cma-token npm start

Deploy to Zeit's now

To be able to deploy to Zeit's now you need to have an activated account. There is a free open source option available.

You can also deploy the demo with now. In your terminal, navigate to the demo/ directory and run:

npm run deploy-demo-now

As soon as the deployment is done you'll have a URL of your GraphQL server copied.

You can also create a deployment for your own space:

SPACE_ID=some-space-id CDA_TOKEN=its-cda-token CMA_TOKEN=your-cma-token npm run deploy-now

Please note:

  • when deploying a server to consume Contentful's "Blog" space template, the command to use is npm run deploy-demo-now; when the demo should be configured to use your own space, the command is npm run deploy-now
  • if you've never used now before, you'll be asked to provide your e-mail; just follow on-screen instructions
  • if you use now's OSS plan (the default one), the source code will be public; it's completely fine: all credentials are passed as env variables and are not available publicly

Programmatic usage

The library can be installed with npm:

npm install --save cf-graphql

Let's assume we've required this module with const cfGraphql = require('cf-graphql'). To create a schema out of your space you need to call cfGraphgl.createSchema(spaceGraph).

What is spaceGraph? It is a graph-like data structure containing descriptions of content types of your space which additionally provide some extra pieces of information allowing the library to create a GraphQL schema.

To prepare this data structure you need to fetch raw content types data from the CMA. Let's create a Contentful client first:

const client = cfGraphql.createClient({
  spaceId: 'some-space-id',
  cdaToken: 'its-cda-token',
  cmaToken: 'your-cma-token'
});

spaceId, cdaToken and cmaToken options are required. You can also pass the following options:

  • locale - a locale code to use when fetching content. If not provided, the default locale of a space is used
  • preview - if true, CPA will be used instead of CDA for fetching content
  • cpaToken - if preview is true then this option has to hold a CPA token

Fetch content types with your client and then pass them to cfGraphql.prepareSpaceGraph(rawCts):

client.getContentTypes()
.then(cfGraphql.prepareSpaceGraph)
.then(spaceGraph => {
  // `spaceGraph` can be passed to `cfGraphql.createSchema`!
});

The last step is to use the schema with a server. A popular choice is express-graphql. The only caveat is how the context is constructed. The library expects the entryLoader key of the context to be set to an instance created with client.createEntryLoader():

// Skipped in snippet: `require` calls, Express app setup, `client` creation.
// `spaceGraph` was fetched and prepared in the previous snippet. In most cases
// you shouldn't be doing it per request, once is fine.
const schema = cfGraphql.createSchema(spaceGraph);

// IMPORTANT: we're passing a function to `graphqlHTTP`: this function will be
// called every time a GraphQL query arrives to create a fresh entry loader.
// You can also use `expressGraphqlExtension` described below.
app.use('/graphql', graphqlHTTP(function () {
  return {
    schema,
    context: {entryLoader: client.createEntryLoader()}
  };
}));

You can see a fully-fledged example in the demo/ directory.

Querying

For each Contentful content type three root-level fields are created:

  • a singular field accepts a required id argument and resolves to a single entity
  • a collection field accepts an optional q, skip and limit arguments and resolves to a list of entities
  • a collection metadata field accepts an optional q argument and resolves to a metadata object (currently comprising only count)

Please note that:

  • the q argument is a query string you could use with the CDA
  • both skip and limit arguments can be used to fetch desired page of results
    • skip defaults to 0
    • limit defaults to 50 and cannot be greater than 1000
  • some query string parameters cannot be used:
    • skip, limit - use collection field arguments instead
    • include, content_type - no need for them, the library will determine and use appropriate values internally
    • locale - all the content is fetched for a single locale. By default the default locale is used; alternate locale can be selected with the locale configuration option of cfGraphql.createClient

Assuming you've got two content types named post and author with listed fields, this query is valid:

{
  authors {
    name
  }

  authors(skip: 10, limit: 10) {
    title
    rating
  }

  _authorsMeta {
    count
  }

  posts(q: "fields.rating[gt]=5") {
    title
    rating
  }

  _postsMeta(q: "fields.rating[gt]=5") {
    count
  }

  post(id: "some-post-id") {
    title
    author
    comments
  }
}

Reference fields will be resolved to:

  • a specific type, if there is a validation that allows only entries of some specific content type to be linked
  • the EntryType, if there is no such constraint. The EntryType is an interface implemented by all the specific types

Example where the author field links only entries of one content type and the related field links entries of multiple content types:

{
  posts {
    author {
      name
      website
    }

    related {
      ... on Tag {
        tagName
      }
      ... on Place {
        location
        name
      }
    }
  }
}

Backreferences (backrefs) are automatically created for links. Assume our post content type links to the author content type via a field named author. Getting an author of a post is easy, getting a list of posts by an author is not. _backrefs mitigate this problem:

{
  authors {
    _backrefs {
      posts__via__author {
        title
      }
    }
  }
}

When using backreferences, there is a couple of things to keep in mind:

  • backrefs may be slow; always test with a dataset which is comparable with what you've got in production
  • backrefs are generated only when a reference field specifies a single allowed link content type
  • _backrefs is prefixed with a single underscore
  • __via__ is surrounded with two underscores; you can read this query out loud like this: "get posts that link to author via the author field"

Helpers

cf-graphql comes with helpers that help you with the cf-graphql integration. These are used inside of the demo application.

expressGraphqlExtension

expressGraphqlExtension is a simple utility producing a function that can be passed directly to the express-graphql middleware.

// Skipped in this snippet: client and space graph creation
const schema = cfGraphql.createSchema(spaceGraph);

const opts = {
  // display the current cf-graphql version in responses
  version: true,
  // include list of the underlying Contentful CDA calls with their timing
  timeline: true,
  // display detailed error information
  detailedErrors: true
};

const ext = cfGraphql.helpers.expressGraphqlExtension(client, schema, opts);
app.use('/graphql', graphqlHTTP(ext));

Important: Most likely don't want to enable timeline and detailedErrors in your production environment.

graphiql

If you want to run your own GraphiQL and don't want to rely on the one shipping with e.g. express-graphql then you could use the graphiql helper.

const ui = cfGraphql.helpers.graphiql({title: 'cf-graphql demo'});
app.get('/', (_, res) => res.set(ui.headers).status(ui.statusCode).end(ui.body));

Contributing

Issue reports and PRs are more than welcomed.

License

MIT

More Repositories

1

contentful.js

JavaScript library for Contentful's Delivery API (node & browser)
TypeScript
1,174
star
2

rich-text

Libraries for handling and rendering Rich Text 📄
TypeScript
529
star
3

the-example-app.nodejs

Example app for Contentful in node.js
JavaScript
431
star
4

forma-36

A design system by Contentful
TypeScript
329
star
5

contentful-cli

The official Contentful command line interface. Use Contentful features straight from the command line!
JavaScript
322
star
6

contentful-migration

🚚 Migration tooling for contentful
TypeScript
320
star
7

contentful-management.js

JavaScript library for Contentful's Management API (node & browser)
TypeScript
264
star
8

extensions

Repository providing samples using the UI Extensions SDK
JavaScript
201
star
9

contentful.swift

A delightful Swift interface to Contentful's content delivery API.
Swift
195
star
10

starter-gatsby-blog

Gatsby starter for a Contentful project from the community.
JavaScript
194
star
11

blog-in-5-minutes

Vue
170
star
12

contentful-export

This tool allows you to export a Contentful space to a JSON dump
JavaScript
160
star
13

field-editors

React components and extensions for building Contentful entry editor
TypeScript
148
star
14

contentful_middleman

Contentful Middleman is an extension to use the Middleman static site generator (Ruby) together with the API-driven Contentful CMS.
Ruby
145
star
15

Stargate

A communication channel from your Mac to your watch.
Swift
135
star
16

contentful.rb

Ruby client for the Contentful Content Delivery API
Ruby
135
star
17

apps

Apps on the Contentful Marketplace and resources to build them
TypeScript
132
star
18

ui-extensions-sdk

A JavaScript library to develop custom apps for Contentful
TypeScript
120
star
19

discovery-app-react

A React.js based version of the Contentful Discovery app
JavaScript
111
star
20

contentful.php

Official PHP Library for the Content Delivery API
PHP
111
star
21

contentful-import

Node module that uses the data provided by contentful-export to import it to contentful space
TypeScript
99
star
22

jekyll-contentful-data-import

Contentful Plugin for the Jekyll Static Site Generator
Ruby
99
star
23

create-contentful-app

Bootstrap a Contentful App
TypeScript
98
star
24

gallery-app-react

A React application example for the gallery space template.
JavaScript
97
star
25

contentful.net

.NET Library for Contentful's Content Delivery and Management API
C#
95
star
26

template-blog-webapp-nextjs

Next.js blog starter template
TypeScript
89
star
27

contentful-metalsmith

A plugin for Metalsmith that pulls content from the Contentful API
JavaScript
86
star
28

vault

Easy persistence of Contentful data for Android over SQLite.
Java
84
star
29

template-marketing-webapp-nextjs

Next.js marketing website starter template
TypeScript
80
star
30

contentful.java

Java SDK for Contentful's Content Delivery API
Java
74
star
31

create-contentful-extension

Create Contentful Extension is a CLI tool for developing in-app extensions without the hassle of managing build configurations.
JavaScript
71
star
32

ContentfulWatchKitExample

Example for a WatchKit app using the Contentful SDK
Swift
71
star
33

gallery-app-android

Android application example for the gallery space template.
Java
68
star
34

template-ecommerce-webapp-nextjs

Next.js ecommerce website starter template
TypeScript
63
star
35

compose-starter-helpcenter-nextjs

A sample website frontend for Compose with Next.js
TypeScript
59
star
36

live-preview

Preview SDK for both the field tagging connection + live content updates
TypeScript
56
star
37

contentful_rails

A ruby gem to help you quickly integrate Contentful into your Rails site
Ruby
52
star
38

contentful.objc

Objective-C SDK for Contentful's Content Delivery API and Content Management API.
Objective-C
50
star
39

contentful-resolve-response

Resolve items & includes of a Contentful API response into a proper object graph
JavaScript
46
star
40

contentful.py

Python client for the Contentful Content Delivery API https://www.contentful.com/developers/documentation/content-delivery-api/
Python
45
star
41

contentful-laravel

Laravel integration for the Contentful SDK.
PHP
44
star
42

contentful_model

A lightweight wrapper around the Contentful api gem, to make it behave more like ActiveRecord
Ruby
44
star
43

contentful-space-sync

Synchronize Contentful spaces
JavaScript
42
star
44

the-example-app.swift

Example app for Contentful in Swift
Swift
42
star
45

covid-19-site-template

#project-covid19
JavaScript
40
star
46

11ty-contentful-starter

Contentful 11ty starter project.
CSS
39
star
47

contentful-management.py

Python client for the Contentful Content Management API https://www.contentful.com/developers/documentation/content-management-api/
Python
36
star
48

product-catalogue-js

Product catalogue in JavaScript
JavaScript
36
star
49

contentful-management.rb

Ruby client for the Contentful Content Management API
Ruby
33
star
50

ContentfulBundle

Symfony Bundle for the Contentful SDK.
PHP
32
star
51

contribution-program

Contribute to the Contentful blog with pieces on "better ways to build websites". Get rewarded for each post you publish.
30
star
52

contentful_express_tutorial

A Simple Express js application Built on top of Contentful
JavaScript
30
star
53

rich-text-renderer.swift

Render Contentful Rich Text fields to native strings and views
Swift
29
star
54

contentful_jekyll_examples

Examples for Contentful and Jekyll Integration
29
star
55

11ty-contentful-gallery

Photo Gallery made using Contentful and 11ty.
Liquid
28
star
56

guide-app-sw

A generic guide app for shop guides
JavaScript
27
star
57

ls-postman-rest-api

26
star
58

gallery-app-ios

An iOS application example for the gallery space template.
Swift
26
star
59

contentful-management.java

Java library for using the Contentful Content Management API
Java
26
star
60

contentful-bootstrap.rb

Contentful CLI tool for getting started with Contentful
Ruby
24
star
61

contentful-graphql-playground-app

Contentful App to integrate GraphQL Playground
TypeScript
23
star
62

wordpress-exporter.rb

Adapter to extract data from Wordpress
Ruby
23
star
63

contentful-database-importer.rb

Adapter to extract data from SQL Databases https://www.contentful.com
Ruby
23
star
64

blog-app-android

Android application example for the blog space template.
Java
22
star
65

contentful-sdk-core

Core modules for the Contentful JS SDKs
TypeScript
22
star
66

contentful-persistence.swift

Simplified persistence for the Contentful Swift Library.
Swift
21
star
67

content-models

A set of example content models build with and for Contentful
19
star
68

product-catalogue-android

Android application example for the product catalogue space template.
Java
19
star
69

the-example-app.graphql.js

Example app for Contentful with GraphQL with React
JavaScript
19
star
70

boilerplate-javascript

Boilerplate project for getting started using javascript with Contentful
JavaScript
19
star
71

the-example-app.php

Example app for Contentful in PHP
PHP
18
star
72

ng-contentful

Contentful module for AngularJS, providing access to the content delivery API
JavaScript
17
star
73

contentful_middleman_examples

A useful collection of examples using the `contentful_middleman` gem
Ruby
17
star
74

the-example-app.py

Example app for Contentful in Python
Python
17
star
75

The-Learning-Demo

Working repo for the new Learning Demo being developed by Learning Services
CSS
17
star
76

contentful-core.php

Foundation library for Contentful PHP SDKs
PHP
16
star
77

guide-app-ios

A generic iOS app for shop guides, styled as a guide to Coffee places.
Objective-C
16
star
78

starter-hydrogen-store

Example store starter template built with Contentful and Hydrogen framework from Shopify
JavaScript
16
star
79

contentful_django_tutorial

A Simple Django Application using Contentful
CSS
16
star
80

contentful-action

JavaScript
15
star
81

contentful-merge

CLI to merge entries between environments
TypeScript
15
star
82

contentful-batch-libs

Library modules used by contentful batch utility CLI tools.
JavaScript
15
star
83

sveltekit-starter

Starter repo to get started with Sveltekit and Contentful
Svelte
15
star
84

contentful-scheduler.rb

Scheduling Server for Contentful entries
Ruby
15
star
85

blog-app-ios

An iOS application example for the blog space template.
Swift
15
star
86

the-example-app.kotlin

The example Android app. See how to connect to a sample space and use kotlin and Contentful unisono.
Kotlin
15
star
87

contentful-social.rb

Contentful Social Publishing Gem
Ruby
14
star
88

discovery-app-android

Contentful Discovery App for Android
Java
14
star
89

discovery-app

iOS app for previewing the content of Contentful Spaces
Objective-C
14
star
90

ls-content-as-code

Example content migration API scripts
JavaScript
13
star
91

blog-app-laravel

Example app using Contentful with Laravel.
PHP
13
star
92

slash-developers

THIS REPOSITORY IS DEPRECATED. Please do not open new PRs or issues.
HTML
13
star
93

node-apps-toolkit

A collection of helpers and utilities for creating NodeJS Contentful Apps
TypeScript
12
star
94

rich-text.php

Utilities for the Contentful Rich Text
PHP
12
star
95

the-example-app.csharp

Example app for Contentful in C#
C#
12
star
96

the-example-app.graphql.swift

The Example App and Contentful GraphQL Endpoint, using Apollo iOS, Contentful/ImageOptions
Swift
12
star
97

contentful-link-cleaner

Cleans up unresolved Entry links in Contentful spaces
JavaScript
11
star
98

tvful

Example for using the Contentful SDK for tvOS apps.
Swift
11
star
99

contentful-sdk-jsdoc

JSDoc template and config for the Contentful JS SDKs
JavaScript
10
star
100

generator.java

Code generator for Contentful models
Shell
10
star