Skip to content

Commit

Permalink
Merge pull request #86 from holidayextras/redirects
Browse files Browse the repository at this point in the history
Add ability to write redirects for Paultons
  • Loading branch information
putvande authored Jan 17, 2023
2 parents 5cadf93 + 69ee625 commit 04dd141
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@holidayextras/static-site-generator",
"version": "9.1.1",
"version": "9.2.0",
"description": "Holiday Extras Static Site Generator in metalsmith / react",
"repository": {
"type": "git",
Expand Down
7 changes: 7 additions & 0 deletions src/getDataSource.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import prismic from './metalsmith-prismic'
import hxseo from './getHXSEOContent'
import writeRedirect from './writeRedirect'
import apiCaller from './apiCaller'
import _ from 'lodash'

Expand All @@ -16,12 +17,18 @@ const getDataSource = (opts) => {
accessToken: opts.dataSource.accessToken,
linkResolver: configLinkResolver || function (ctx, doc) {
if (doc.isBroken) return ''

// create redirect script if needed
writeRedirect(doc.data)

// Page url
if (_.has(doc, 'data.slug.json.value')) {
const regExpDomain = new RegExp(`.*${opts.config.domainSettings.domainLive}`)
// Strip domain (+ everything before it) off of the slug in case it was added by mistake
const slug = doc.data.slug.json.value
return slug.replace(regExpDomain, '')
}

return '/' + doc.uid
}
})
Expand Down
22 changes: 22 additions & 0 deletions src/writeRedirect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import fs from 'fs'

const writeRedirect = (documentData) => {
// Prismic custom field with redirect value
const redirectValue = documentData?.redirect?.json?.value
// Prismic custom field for slug or UID which every document has by default
const pageUrl = documentData?.slug?.json?.value || documentData.uid
if (!redirectValue || !pageUrl || !redirectValue.includes('https://')) return

try {
const redirectCommand = `
aws s3 cp s3://$BUCKET/${pageUrl}.html s3://$BUCKET/${pageUrl}.html --website-redirect ${redirectValue}
aws s3 cp s3://$BUCKET/${pageUrl} s3://$BUCKET/${pageUrl} --website-redirect ${redirectValue}`
if (!fs.existsSync('./bin')) fs.mkdirSync('./bin')
fs.appendFileSync('./bin/redirects.sh', redirectCommand, { mode: 0o755 })
console.log(`Added redirect for ${pageUrl} to ${redirectValue}`)
} catch (err) {
console.log(`Writing redirect to bash file for ${pageUrl} has failed.`, err)
}
}

export default writeRedirect

0 comments on commit 04dd141

Please sign in to comment.