Files
the-example-app-nodejs/app.js
Benedikt Rötsch 7ad2c1fa4f refactor: Cleanup (#21)
* refactor(routes): remove unused sitemap route

* style(comments): enforce consistent comment style

* style(exports): enforce consistent export style

* chore: Add jsDoc for contentful service

* chore: Add jsDoc for contentful service \n \n closes #23

* refactor(app): move query parameter comment to right position and mention comment route middleware

* test(npm): add temporary test script

* refactor(middlewares): split up bootstrap middleware - fixes #23759

* refactor(cookies): use constances to give context the maxAge cookie setting

* refactor(variables): use more descriptive names for variables

* space became spaceId when it was just the id not the full space instance
* all (access) token variable name variants became [api-type]Token
* all clients are now called deliveryClient or previewClient
* cpa and cda only remain when they are used as actual API id
* env variables names adjusted

* perf(helpers): only run marked when content is not empty

* refactor(comments): fix typos

* refactor(comments): add hint why error is logged to console in settings

* chore: Add comments to routes and services

* refactor(requires): order and group requires

* fix(settings): add validation for wrong preview token

* chore: Add comments to routes

* chore: fix typo

* chore: console.error -> throw

* chore: move cookie name to a constant

* chore: Fix app.js comment

* typo: removing t

* chore: typos

* chore: removed unnecessary comment line sign

* chore: newline for readabillity

* chore: remove dangling `t`

* chore: remove `t`, add `l`

* chore: typos

* Fleshed out title

* build(npm): remove unused dependencies

* build(npm): upgrade to latest stable contentful sdk

* chore: Addressing David feedbak

* fix(credentials): update to match the new space

* chore: Addressing code review comments

* chore: Addressing code review comments

* chore: res -> response, req-> request

* chore: include exactly what we need

* chore: Address JPs comments

* chore: Address JPs comments

* chore: Address Fredericks comments

* chore: Address Fredericks comments

* fixup! chore: Address Fredericks comments

* fixup! fixup! chore: Address Fredericks comments

* fixup! fixup! fixup! chore: Address Fredericks comments

* fixup! fixup! fixup! fixup! chore: Address Fredericks comments

* fixup! fixup! fixup! fixup! fixup! chore: Address Fredericks comments

* fixup! fixup! fixup! fixup! fixup! fixup! chore: Address Fredericks comments
2017-11-07 17:33:32 +01:00

137 lines
4.0 KiB
JavaScript

const path = require('path')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const express = require('express')
const logger = require('morgan')
const querystring = require('querystring')
// Load environment variables using dotenv
require('dotenv').config({ path: 'variables.env' })
const helpers = require('./helpers')
const breadcrumb = require('./lib/breadcrumb')
const routes = require('./routes/index')
const { initClients, getSpace } = require('./services/contentful')
const { updateCookie } = require('./lib/cookies')
const app = express()
const SETTINGS_NAME = 'theExampleAppSettings'
// View engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use(breadcrumb())
// Set our application state based on environment variables or query parameters
app.use(async function (request, response, next) {
// Set default settings based on environment variables
let settings = {
spaceId: process.env.CONTENTFUL_SPACE_ID,
deliveryToken: process.env.CONTENTFUL_DELIVERY_TOKEN,
previewToken: process.env.CONTENTFUL_PREVIEW_TOKEN,
editorialFeatures: false,
// Overwrite default settings using those stored in a cookie
...request.cookies.theExampleAppSettings
}
// Allow setting of API credentials via query parameters
const { space_id, preview_token, delivery_token } = request.query
if (space_id && preview_token && delivery_token) { // eslint-disable-line camelcase
settings = {
...settings,
spaceId: space_id,
deliveryToken: delivery_token,
previewToken: preview_token
}
updateCookie(response, SETTINGS_NAME, settings)
}
// Allow enabling of editorial features via query parameters
const { enable_editorial_features } = request.query
if (enable_editorial_features !== undefined) { // eslint-disable-line camelcase
delete request.query.enable_editorial_features
settings.editorialFeatures = true
updateCookie(response, SETTINGS_NAME, settings)
}
initClients(settings)
response.locals.settings = settings
next()
})
// Make data available for our views to consume
app.use(async function (request, response, next) {
// Set active api based on query parameter
const apis = [
{
id: 'cda',
label: 'Delivery (published content)'
},
{
id: 'cpa',
label: 'Preview (draft content)'
}
]
response.locals.currentApi = apis
.find((api) => api.id === (request.query.api || 'cda'))
// Get enabled locales from Contentful
const space = await getSpace()
response.locals.locales = space.locales
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
}
// Inject custom helpers
response.locals.helpers = helpers
// 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
next()
})
// Initialize the route handling
// Check ./routes/index.js to get a list of all implemented routes
app.use('/', routes)
// Catch 404 and forward to error handler
app.use(function (request, response, next) {
var err = new Error('Not Found')
err.status = 404
next(err)
})
// Error handler
app.use(function (err, request, response, next) {
// Set locals, only providing error in development
response.locals.error = request.app.get('env') === 'development' ? err : {}
// Render the error page
response.status(err.status || 500)
response.render('error')
})
module.exports = app