Production deploy 16:00 (#70)

* Production (#44)

* test: Fix integration test

* fix: Fix Editorial feature

* chore(localization): move locales to i18n folder

* feat(modules): add image caption and shadow

* fix: clarify German translation🇩🇪

* chore(localization): fix typo (#47)

* Split first paragraph into sections (#46)

* feat(controls): add help text to API dropdown

* fix(style): simplify header and fix mobile design

* fix(style): simplify footer and fix mobile design

* fix(style): update stylesheet and scripts file

* test(e2e): adjust tests and make them fail on CI

* language fixes

* rename labels to use full api name

* Refactor entry state toggle (#48)

* chore(editorialFeatures): extract editorial features toggle

* chore(refactor): rename function to make more contextual sense

* Fix breadcrumb and add test for locales (#49)

* test(unit): add test to check for locale consistency

* fix(breadcrumb): translate lessons route

* Change readme url to http from https (#52)

* tests(e2e): expect only 2 courses

* fix(cookies): fix variable naming and extend to two days maxAge

* Change text on next lesson button (#54)

* Retranslate advancedLabel

* fix(translations): do not break on vim temp files. This is dedicated to JP

* fix(analytics): use correct app-id

* Add instructions to seed a space to readme (#61)

* Change modal text; add link to model's repo to localization files (#57)

* fix(links): link correct GH repository

* fix(i18n): adjust view on github link label

* fix(style): move GitHub link to the left

* new screenshot

* Update README.md (#63)

* Update README.md

* Update README.md

* Https mistake and Heroku buton

* fixup

* fixup

* feat(heroku): add app.json

* docs(README): add linebreak

* docs(README): minor adjustments

* fix(tracking): add link click tracking to snowplow

* Add translation for edit in the web app (#64)

* chore(typo): fix error message (#67)

* chore(update): remove image rendering on lessons (#65)

* chore: Improve error page (#66)

* chore: Improve error page

* fix: Fix middlware order

* fix: Remove console.log

* fix:  no more duplicate error messges (#71)

* fix: Fix middlware order

* fix: Remove console.log

* feat: Uniq error meassages

* fix: fix cli link (#72)

* Add instructions to run app as Docker container (#68)
This commit is contained in:
Khaled Garbaya
2017-11-16 14:42:28 +01:00
committed by GitHub
parent 5a20ed0dbc
commit c944885446
15 changed files with 187 additions and 59 deletions

2
.dockerignore Normal file
View File

@@ -0,0 +1,2 @@
node_modules
npm-debug.log

15
Dockerfile Normal file
View File

@@ -0,0 +1,15 @@
FROM node:9
WORKDIR /app
RUN npm install -g contentful-cli
COPY package.json .
RUN npm install
COPY . .
USER node
EXPOSE 3000
CMD ["npm", "run", "start:dev"]

107
README.md
View File

@@ -1,35 +1,41 @@
## The node.js Example App
## The node.js example app
The node.js Example App aims at getting across the very basics of how to work with our headless content management system and how to build apps using our officially supported JavaScript SDK. Youll learn best practices for using the SDK to deliver content to your app and additionally learn some techniques for modelling your content in Contentful.
The node.js example app teaches the very basics of how to work with Contentful:
We hope this app will give you a better understanding of how decoupling content from its presentation enables greater flexibility and facilitates shipping higher quality software more quickly.
- consume content from the Contentful Delivery and Preview APIs
- model content
- edit content through the Contentful web app
Contentful is a content management platform for web applications, mobile apps and connected devices. It allows you to create, edit and manage content in the cloud and publish it anywhere via powerful API. Contentful offers tools for managing editorial teams and enabling cooperation between organizations.
The app demonstrates how decoupling content from its presentation enables greater flexibility and facilitates shipping higher quality software more quickly.
<a href="https://the-example-app-nodejs.herokuapp.com/" target="_blank"><img src="https://images.contentful.com/qz0n5cdakyl9/4GZmvrdodGM6CksMCkkAEq/700a527b8203d4d3ccd3c303c5b3e2aa/the-example-app.png" alt="Screenshot of the example app"/></a>
You can see a hosted version of `The node.js example app` on <a href="https://the-example-app-nodejs.herokuapp.com/" target="_blank">Heroku</a>.
## What is Contentful?
Contentful is content infrastructure for web applications, mobile apps and connected devices. It allows you to create, edit and manage content in the cloud and publish it anywhere via powerful APIs. Contentful offers tools for editorial teams and enabling cooperation between organizations.
## Requirements
* Node 8
* Git
* Contentful CLI (only for write access)
Without any changes, this app is connected to a Contentful space that is not publicly accessible. The full end-to-end Contentful experience requires you to clone this space to your own Contentful account, and enables you to see how content editing in the Contentful web app and see those changes propagate to this running application. Signing up and getting started with our free plan is... free!
Without any changes, this app is connected to a Contentful space with read-only access. To experience the full end-to-end Contentful experience, you need to connect the app to a Contentful space with read _and_ write access. This enables you to see how content editing in the Contentful web app works and how content changes propagate to this app.
## Common setup
You can clone the space for this example app to your own Contentful account by using our CLI tool.
```
contentful space seed -s '<SPACE_ID>' -t the-example-app
```
If you do not have the Contentful CLI installed you can find instructions on installation and usage [here](https://github.com/contentful/contentful-cli). For more information on the content model check out [this repo](https://github.com/contentful/content-models/tree/master/the-example-app/README.md).
If you do not have the Contentful CLI installed you can find instructions on installation and usage [here](https://www.npmjs.com/package/contentful-cli). For more information on the content model check out [this repo](https://github.com/contentful/content-models/tree/master/the-example-app/README.md).
Once youve created a space, you can change the credentials in the variables.env. If you dont feel like changing code immediately, you can also inject credentials via url parameters like so:
```
http://localhost:3000?space_id=<YOUR_CLONED_SPACE_ID>&delivery_token=<YOUR_DELIVERY_TOKEN>&preview_token=<YOUR_PREVIEW_TOKEN>
```
## Installing the Node.js app
Clone the repo and install the dependencies.
```bash
git clone https://github.com/contentful/the-example-app.nodejs.git
@@ -39,13 +45,86 @@ git clone https://github.com/contentful/the-example-app.nodejs.git
npm install
```
## Running the Node.js app
## Steps for read-only access
To start the server, run the following
To start the express server, run the following
```bash
npm run start:dev
```
Open [https://localhost:3000](https://localhost:3000) and take a look around. If you have configured the app to connect to a space that you own, use [https://localhost:3000?enable_editorial_features](https://localhost:3000?enable_editorial_features). This URL flag adds an “Edit” button in the app on every editable piece of content which will take you back to Contentful web app where you can make changes. It also adds “Draft” and “Pending Changes” status indicators to all content if relevant.
Open [http://localhost:3000](http://localhost:3000) and take a look around.
## Steps for read and write access (recommended)
Step 1: Install the [Contentful CLI](https://www.npmjs.com/package/contentful-cli)
Step 2: Login to Contentful through the CLI. It will help you to create a [free account](https://www.contentful.com/sign-up/) if you don't have one already.
```
contentful login
```
Step 3: Create a new space
```
contentful space create --name 'My space for the example app'
```
Step 4: Seed the new space with the content model. Replace the `SPACE_ID` with the id returned from the create command executed in step 3
```
contentful space seed -s '<SPACE_ID>' -t the-example-app
```
Step 5: Head to the Contentful web app's API section and grab `SPACE_ID`, `DELIVERY_ACCESS_TOKEN`, `PREVIEW_ACCESS_TOKEN`.
Step 6: Open `variables.env` and inject your credentials so it looks like this
```
NODE_ENV=development
CONTENTFUL_SPACE_ID=<SPACE_ID>
CONTENTFUL_DELIVERY_TOKEN=<DELIVERY_ACCESS_TOKEN>
CONTENTFUL_PREVIEW_TOKEN=<PREVIEW_ACCESS_TOKEN>
PORT=3000
```
Step 7: To start the express server, run the following
```bash
npm run start:dev
```
Final Step:
Open [http://localhost:3000?enable_editorial_features](http://localhost:3000?enable_editorial_features) and take a look around. This URL flag adds an “Edit” button in the app on every editable piece of content which will take you back to Contentful web app where you can make changes. It also adds “Draft” and “Pending Changes” status indicators to all content if relevant.
## Deploy to Heroku
You can also deploy this app to Heroku:
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy)
## Use Docker
You can also run this app as a Docker container:
Step 1: Clone the repo
```bash
git clone https://github.com/contentful/the-example-app.nodejs.git
```
Step 2: Build the Docker image
```bash
docker build -t the-example-app.nodejs .
```
Step 3: Run the Docker container locally:
```bash
docker run -p 3000:3000 -d the-example-app.nodejs
```
If you created your own Contentful space, you can use it by overriding the following environment variables:
```bash
docker run -p 3000:3000 \
-e CONTENTFUL_SPACE_ID=<SPACE_ID> \
-e CONTENTFUL_DELIVERY_TOKEN=<DELIVERY_ACCESS_TOKEN> \
-e CONTENTFUL_PREVIEW_TOKEN=<PREVIEW_ACCESS_TOKEN> \
-d the-example-app.nodejs
```

49
app.js
View File

@@ -16,6 +16,7 @@ const breadcrumb = require('./lib/breadcrumb')
const settings = require('./lib/settings')
const routes = require('./routes/index')
const { getSpace } = require('./services/contentful')
const { catchErrors } = require('./handlers/errorHandlers')
const app = express()
@@ -43,22 +44,18 @@ app.use(function (req, res, next) {
app.use(settings)
// Make data available for our views to consume
app.use(async function (request, response, next) {
app.use(catchErrors(async function (request, response, next) {
// Get enabled locales from Contentful
const space = await getSpace()
response.locals.locales = space.locales
response.locals.locales = [{code: 'en-US', name: 'U.S. English'}]
response.locals.currentLocale = response.locals.locales[0]
// Inject custom helpers
response.locals.helpers = helpers
const defaultLocale = response.locals.locales
.find((locale) => locale.default)
if (request.query.locale) {
response.locals.currentLocale = space.locales
.find((locale) => locale.code === request.query.locale)
}
if (!response.locals.currentLocale) {
response.locals.currentLocale = defaultLocale
}
// Make query string available in templates to render links properly
const qs = querystring.stringify(request.query)
response.locals.queryString = qs ? `?${qs}` : ''
response.locals.query = request.query
response.locals.currentPath = request.path
// Initialize translations and include them on templates
initializeTranslations()
@@ -79,17 +76,23 @@ app.use(async function (request, response, next) {
response.locals.currentApi = apis
.find((api) => api.id === (request.query.api || 'cda'))
// Inject custom helpers
response.locals.helpers = helpers
const space = await getSpace()
response.locals.locales = space.locales
// Make query string available in templates to render links properly
const qs = querystring.stringify(request.query)
response.locals.queryString = qs ? `?${qs}` : ''
response.locals.query = request.query
response.locals.currentPath = request.path
const defaultLocale = response.locals.locales
.find((locale) => locale.default)
if (request.query.locale) {
response.locals.currentLocale = space.locales
.find((locale) => locale.code === request.query.locale)
}
if (!response.locals.currentLocale) {
response.locals.currentLocale = defaultLocale
}
next()
})
}))
app.use(breadcrumb())
@@ -108,7 +111,7 @@ app.use(function (request, response, next) {
app.use(function (err, request, response, next) {
// Set locals, only providing error in development
response.locals.error = request.app.get('env') === 'development' ? err : {}
response.locals.error.status = err.status || 500
// Render the error page
response.status(err.status || 500)
response.render('error')

12
app.json Normal file
View File

@@ -0,0 +1,12 @@
{
"name": "The Example App",
"description": "This is \"The Example App\", a reference for building your own applications using Contentful.",
"keywords": [
"contentful",
"example"
],
"website": "https://www.contentful.com/",
"repository": "https://github.com/contentful/the-example-app.nodejs",
"logo": "https://the-example-app-nodejs.herokuapp.com/images/logo-node.svg",
"success_url": "/"
}

View File

@@ -30,6 +30,8 @@
snowplow('trackPageView');
snowplow('enableLinkClickTracking')
const space_id = decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent('space_id').replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
snowplow('trackSelfDescribingEvent', {

View File

@@ -7,6 +7,9 @@
module.exports.catchErrors = (fn) => {
return function (request, response, next) {
return fn(request, response, next).catch((e) => {
if (e.response) {
e.status = e.response.status
}
next(e)
})
}

View File

@@ -79,5 +79,7 @@
"previewKeyInvalidLabel": "Ihr Preview API Zugangsschlüssel ist ungültig.",
"beginnerLabel": "Anfänger",
"intermediateLabel": "Fortgeschrittener",
"advancedLabel": "Experte"
"advancedLabel": "Experte",
"editInTheWebAppLabel": "In der web app bearbeiten",
"error404Route": "Ein nicht unterstützter HTTP Route"
}

View File

@@ -45,7 +45,7 @@
"startCourseLabel": "Start course",
"categoriesLabel": "Categories",
"allCoursesLabel": "All courses",
"somethingWentWrongLabel": "Oops Something went wrong",
"somethingWentWrongLabel": "Oops, something went wrong",
"tryLabel": "Try",
"contentModelChangedErrorLabel": "Check if the content model has changed",
"draftOrPublishedErrorLabel": "Check the selection has content in draft or published state (for Preview or Delivery)",
@@ -79,5 +79,7 @@
"previewKeyInvalidLabel": "Your Preview API key is invalid.",
"beginnerLabel": "Beginner",
"intermediateLabel": "Intermediate",
"advancedLabel": "Advanced"
"advancedLabel": "Advanced",
"editInTheWebAppLabel": "Edit in the web app",
"error404Route": "a non supported route"
}

View File

@@ -29,6 +29,7 @@
"dotenv": "^4.0.0",
"express": "~4.14.0",
"helmet": "^3.9.0",
"loadash": "^1.0.0",
"marked": "^0.3.6",
"morgan": "~1.7.0",
"pug": "~2.0.0-beta6"

View File

@@ -6,7 +6,7 @@ const { createClient } = require('contentful')
const { initClients, getSpace } = require('./../services/contentful')
const { updateCookie } = require('../lib/cookies')
const { translate } = require('../i18n/i18n')
const { uniqWith, isEqual } = require('lodash')
const SETTINGS_NAME = 'theExampleAppSettings'
async function renderSettings (response, opts) {
@@ -58,7 +58,7 @@ module.exports.getSettings = async (request, response, next) => {
*/
module.exports.postSettings = async (request, response, next) => {
const currentLocale = response.locals.currentLocale
const errorList = []
let errorList = []
const { spaceId, deliveryToken, previewToken, editorialFeatures } = request.body
const settings = {
spaceId,
@@ -143,7 +143,7 @@ module.exports.postSettings = async (request, response, next) => {
}
}
}
errorList = uniqWith(errorList, isEqual)
// If no errors, then cache the new settings in the cookie
if (!errorList.length) {
// Store new settings

View File

@@ -9,15 +9,23 @@ block content
h1 #{translate('somethingWentWrongLabel', currentLocale.code)} (#{error.status})
h2 #{translate('tryLabel', currentLocale.code)}:
ul
li #{translate('contentModelChangedErrorLabel', currentLocale.code)}
li #{translate('draftOrPublishedErrorLabel', currentLocale.code)}
li #{translate('localeContentErrorLabel', currentLocale.code)}
li #{translate('verifyCredentialsErrorLabel', currentLocale.code)}
case error.status
when 404
li #{translate('error404Route', currentLocale.code)}
li #{translate('draftOrPublishedErrorLabel', currentLocale.code)}
when 400
li #{translate('contentModelChangedErrorLabel', currentLocale.code)}
when 401
li #{translate('verifyCredentialsErrorLabel', currentLocale.code)}
li #{translate('localeContentErrorLabel', currentLocale.code)}
if error.stack
li #{translate('stackTraceErrorLabel', currentLocale.code)}
if error.response
h2 #{translate('errorLabel', currentLocale.code)}
pre.error__stack-trace
code.shell #{helpers.dump(error.response.data)}
h2 #{translate('stackTraceLabel', currentLocale.code)}
pre.error__stack-trace
code.shell #{error.stack}
if error.stack
h2 #{translate('stackTraceLabel', currentLocale.code)}
pre.error__stack-trace
code.shell #{error.stack}

View File

@@ -1,6 +1,7 @@
mixin breadcrumb
nav.breadcrumb
ul
each item in breadcrumb
li
a(href=`${item.url}${queryString}`) #{item.label}
if breadcrumb
nav.breadcrumb
ul
each item in breadcrumb
li
a(href=`${item.url}${queryString}`) #{item.label}

View File

@@ -11,7 +11,7 @@ mixin editorialFeatures(entry)
href=`https://app.contentful.com/spaces/${settings.spaceId}/entries/${entry.sys.id}`
target='_blank'
rel='noopener'
) Edit in the web app
) #{translate('editInTheWebAppLabel', currentLocale.code)}
.editorial-features__hint-wrapper
svg.editorial-features__hint-icon
use(xlink:href='/icons/icons.svg#info')

View File

@@ -7,8 +7,6 @@ mixin lesson(lesson, course, nextLesson)
.lesson
h1.lesson__title #{lesson.fields.title}
+editorialFeatures(lesson)
if lesson.fields.image
img.lesson__image(src=`${lesson.fields.image.fields.file.url}` alt=`${lesson.fields.image.fields.title}`)
.lesson__modules
each module in lesson.fields.modules
if module.sys.contentType