Files
the-example-app-nodejs/routes/settings.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

175 lines
4.4 KiB
JavaScript

/**
* This module renders the settings page when `settings` route is requested
* it also saves the settings to a cookie
*/
const { createClient } = require('contentful')
const { initClients, getSpace } = require('./../services/contentful')
const { updateCookie } = require('../lib/cookies')
const SETTINGS_NAME = 'theExampleAppSettings'
async function renderSettings (response, opts) {
// Get connected space to display the space name on top of the settings
let space = false
try {
space = await getSpace()
} catch (error) {
// We throw the error here, it will be handled by the error middleware
// We keep space false to ensure the "Connected to" box is not shown.
throw (error)
}
response.render('settings', {
title: 'Settings',
errors: {},
hasErrors: false,
success: false,
space,
...opts
})
}
/**
* Renders the settings page when `/settings` route is requested
*
* @param request - Object - Express request
* @param response - Object - Express response
* @param next - Function - Express callback
*
* @returns {undefined}
*/
module.exports.getSettings = async (request, response, next) => {
const { settings } = response.locals
await renderSettings(response, {
settings
})
}
/**
* Save settings when POST request is triggered to the `/settings` route
* and render the settings page
*
* @param request - Object - Express request
* @param response - Object - Express response
* @param next - Function - Express callback
*
* @returns {undefined}
*/
module.exports.postSettings = async (request, response, next) => {
const errorList = []
const { spaceId, deliveryToken, previewToken, editorialFeatures } = request.body
const settings = {
spaceId,
deliveryToken,
previewToken,
editorialFeatures: !!editorialFeatures
}
// Validate required fields.
if (!spaceId) {
errorList.push({
field: 'spaceId',
message: 'This field is required'
})
}
if (!deliveryToken) {
errorList.push({
field: 'deliveryToken',
message: 'This field is required'
})
}
if (!previewToken) {
errorList.push({
field: 'previewToken',
message: 'This field is required'
})
}
// Validate space and delivery access token.
if (spaceId && deliveryToken) {
try {
await createClient({
space: spaceId,
accessToken: deliveryToken
}).getSpace()
} catch (err) {
if (err.response.status === 401) {
errorList.push({
field: 'deliveryToken',
message: 'Your Delivery API key is invalid.'
})
} else if (err.response.status === 404) {
errorList.push({
field: 'spaceId',
message: 'This space does not exist or your access token is not associated with your space.'
})
} else {
errorList.push({
field: 'deliveryToken',
message: `Something went wrong: ${err.response.data.message}`
})
}
}
}
// Validate space and CPA access token.
if (spaceId && previewToken) {
try {
await createClient({
space: spaceId,
accessToken: previewToken,
host: 'preview.contentful.com'
}).getSpace()
} catch (err) {
if (err.response.status === 401) {
errorList.push({
field: 'previewToken',
message: 'Your Preview API key is invalid.'
})
} else if (err.response.status === 404) {
errorList.push({
field: 'spaceId',
message: 'This space does not exist or your delivery token is not associated with your space.'
})
} else {
errorList.push({
field: 'previewToken',
message: `Something went wrong: ${err.response.data.message}`
})
}
}
}
// When no errors occurred
if (!errorList.length) {
// Store new settings
updateCookie(response, SETTINGS_NAME, settings)
response.locals.settings = settings
// Reinit clients
initClients(settings)
}
// Generate error dictionary
// Format: { FIELD_NAME: [array, of, error, messages] }
const errors = errorList.reduce((errors, error) => {
return {
...errors,
[error.field]: [
...(errors[error.field] || []),
error.message
]
}
}, {})
await renderSettings(response, {
settings,
errors,
hasErrors: errorList.length > 0,
success: errorList.length === 0
})
}