From 88e843857109ac8458f2dd3da914efc2de7479de Mon Sep 17 00:00:00 2001
From: Jonathan Jahr <jonjahr@gmail.com>
Date: Tue, 3 May 2022 13:48:54 -0700
Subject: [PATCH] Move Contentful access token logic to shared function so that
 services/contentful.coffee can use it.  Trying to fix bug where no routes
 were generated when CONTENTFUL_PREVIEW=true.

---
 config/concerns/cms.coffee | 7 ++-----
 services/contentful.coffee | 8 +++++++-
 2 files changed, 9 insertions(+), 6 deletions(-)

diff --git a/config/concerns/cms.coffee b/config/concerns/cms.coffee
index 91b9fe1..c0ae9d0 100644
--- a/config/concerns/cms.coffee
+++ b/config/concerns/cms.coffee
@@ -2,6 +2,7 @@
 Add configuration required to interact with CMS choice
 ###
 { join } = require 'path'
+{ getAccessToken } = require '../../services/contentful'
 module.exports = ({ cms }) ->
 	return unless cms
 
@@ -19,11 +20,7 @@ module.exports = ({ cms }) ->
 					CONTENTFUL_PREVIEW: process.env.CONTENTFUL_PREVIEW
 
 					# Don't expose the preview access token when it's not being used
-					CONTENTFUL_ACCESS_TOKEN: do ->
-						if process.env.CONTENTFUL_PREVIEW and
-							previewToken = process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN
-						then previewToken
-						else process.env.CONTENTFUL_ACCESS_TOKEN
+					CONTENTFUL_ACCESS_TOKEN: getAccessToken()
 
 		)
 	}
diff --git a/services/contentful.coffee b/services/contentful.coffee
index 74a60c3..769baae 100644
--- a/services/contentful.coffee
+++ b/services/contentful.coffee
@@ -7,13 +7,19 @@ import axios from 'axios'
 # when services/contentful was imported from a Nuxt module
 nonEmpty = (array) -> array.filter (val) -> !!val
 
+export getAccessToken = ->
+	if process.env.CONTENTFUL_PREVIEW and
+		previewToken = process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN
+	then previewToken
+	else process.env.CONTENTFUL_ACCESS_TOKEN
+
 # Make a Contentful client
 client = axios.create
 	baseURL: 'https://graphql.contentful.com/content/v1/spaces/' +
 		process.env.CONTENTFUL_SPACE
 	headers:
 		'Content-Type': 'application/json'
-		'Authorization': 'Bearer ' + process.env.CONTENTFUL_ACCESS_TOKEN
+		'Authorization': 'Bearer ' + getAccessToken()
 
 # Retry requests when met with Contentful API rate limits.
 # https://www.contentful.com/developers/docs/references/graphql/#/introduction/api-rate-limits