Skip to content

Commit

Permalink
Merge branch 'bose/2115' into staging
Browse files Browse the repository at this point in the history
  • Loading branch information
padms committed Mar 7, 2024
2 parents 59a8341 + 4223a48 commit 31026fe
Show file tree
Hide file tree
Showing 12 changed files with 3,026 additions and 329 deletions.
6 changes: 6 additions & 0 deletions web/common/helpers/getPaths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ const getDocumentsForLocale = async (type: 'news' | 'localNews' | 'magazine', lo
return data
}

// Check if a given path exists in Sanity or not
export const pathExistsInSanity = async (pathname: string, isPreview = false): Promise<boolean> => {
const article = await getDocumentBySlug(pathname, isPreview)
return Boolean(article)
}

// Get a Sanity document by given slug
// Only include drafts if preview mode is enabled
export const getDocumentBySlug = async (slug: string, isPreview = false) => {
Expand Down
12 changes: 11 additions & 1 deletion web/common/helpers/redirects.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { getClient } from '../../lib/sanity.server'
import { redirects, externalRedirects, RedirectsType, ExternalRedirectsType } from '../../lib/queries/redirects'
import {
redirects,
externalRedirects,
allExternalRedirects,
RedirectsType,
ExternalRedirectsType,
} from '../../lib/queries/redirects'

export const getRedirectUrl = async (slug: string, locale: string): Promise<RedirectsType> => {
return getClient(false).fetch(redirects, { slug: slug, slugWithLocale: `/${locale}${slug}` })
Expand All @@ -9,6 +15,10 @@ export const getExternalRedirectUrl = async (slug: string, locale: string): Prom
return getClient(false).fetch(externalRedirects, { slug: slug, slugWithLocale: `/${locale}${slug}` })
}

export const getAllExternalRedirects = async (): Promise<ExternalRedirectsType> => {
return getClient(false).fetch(allExternalRedirects)
}

export const getDnsRedirect = (host: string, pathname: string) => {
const dns = host.replace('http://', '').replace('https://', '').replace('www.', '')

Expand Down
7 changes: 7 additions & 0 deletions web/lib/queries/redirects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,10 @@ export const externalRedirects = /* groq */ `
to
}
`

export const allExternalRedirects = /* groq */ `
*[_type == "externalRedirect" && ${noDrafts}]{
from,
to
}
`
5 changes: 4 additions & 1 deletion web/lib/sanity.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
import { createClient } from '@sanity/client'
import { sanityConfig } from './config'

export const sanityClient = createClient(sanityConfig)
// add perspective: 'published'
export const sanityClient = createClient({
...sanityConfig,
})

export const sanityClientWithEquinorCDN = createClient({
...sanityConfig,
Expand Down
50 changes: 3 additions & 47 deletions web/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,18 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { getRedirectUrl, getDnsRedirect, getExternalRedirectUrl } from './common/helpers/redirects'
import { getDnsRedirect } from './common/helpers/redirects'
import { NextRequest, NextResponse } from 'next/server'
import { getLocaleFromName } from './lib/localization'
import { Flags } from './common/helpers/datasetHelpers'
import { getDocumentBySlug } from './common/helpers/getPaths'
import archivedNews from './lib/archive/archivedNewsPaths.json'

const PERMANENT_REDIRECT = 301
//const TEMPORARY_REDIRECT = 302
const PUBLIC_FILE = /\.(.*)$/
const DOT_HTML = '.html'
const IS_ARCHIVED_NEWS_DOWNLOADS = /(.*)\/news\/archive\/[0-9]{4}\/[0-9]{2}\/[0-9]{2}\/downloads\/(.*)\.(.*)$/

// Check if a given path exists in Sanity or not
const pathExistsInSanity = async (pathname: string, isPreview = false): Promise<boolean> => {
const article = await getDocumentBySlug(pathname, isPreview)
return Boolean(article)
}

// Check if preview mode is enabled in Sanity
const isPreviewEnabled = (request: NextRequest): boolean => {
const { searchParams } = request.nextUrl
const previewCookie = request.cookies.get('__next_preview_data')
const previewParam = searchParams.get('preview')

if (previewCookie && previewParam) return true

return false
}

export async function middleware(request: NextRequest) {
const { origin, locale } = request.nextUrl
const pathname = decodeURI(request.nextUrl.pathname)
const isDotHtml = pathname.slice(-5) === DOT_HTML
const isPreview = isPreviewEnabled(request)

// Rewrite the correct path for assets in download section of achived news (older than 2016)
if (IS_ARCHIVED_NEWS_DOWNLOADS.test(pathname) && (Flags.IS_DEV || Flags.IS_GLOBAL_PROD)) {
Expand All @@ -58,32 +37,9 @@ export async function middleware(request: NextRequest) {
return NextResponse.redirect(dnsRedirect, PERMANENT_REDIRECT)
}

// Redirect external links to news which is now archived if link doesn't exist in Sanity
if (Flags.HAS_ARCHIVED_NEWS && pathname.startsWith('/news') && !pathname.startsWith('/news/archive')) {
const existsInSanity = await pathExistsInSanity(pathname, isPreview)
if (!existsInSanity) {
const archivedPath = pathname.replace('news', 'news/archive')
const existsInArchive = archivedNews.some((e) => e.slug === archivedPath)
if (existsInArchive) return NextResponse.redirect(`${origin}${archivedPath}`, PERMANENT_REDIRECT)
}
}

// Redirect to the same url lowercased if necessary
if (pathname !== pathname.toLowerCase() && !pathname.includes('/news/archive')) {
return NextResponse.redirect(`${origin}${pathname.toLowerCase()}`, PERMANENT_REDIRECT)
}

// Check if an external redirect exists in sanity
const externalRedirect = await getExternalRedirectUrl(pathname, request.nextUrl.locale)
if (externalRedirect) {
return NextResponse.redirect(externalRedirect.to, PERMANENT_REDIRECT)
}

// Check if an internal redirect exists in sanity
const redirect = await getRedirectUrl(pathname, request.nextUrl.locale)
if (redirect) {
const locale = getLocaleFromName(redirect.lang)
return NextResponse.redirect(`${origin}/${locale}${redirect.to !== '/' ? redirect.to : ''}`, PERMANENT_REDIRECT)
if (pathname !== pathname.toLowerCase()) {
return NextResponse.rewrite(`${origin}${pathname.toLowerCase()}`)
}

// Check if pathname ends with .html
Expand Down
32 changes: 4 additions & 28 deletions web/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import withBundleAnalyzer from '@next/bundle-analyzer'
import nextTranspileModules from 'next-transpile-modules'
import { dataset, defaultLanguage, domain, languages } from './languages.js'
import securityHeaders from './securityHeaders.js'
import { getAllRedirects } from './redirects.js'

const withTM = nextTranspileModules(['friendly-challenge'])

Expand Down Expand Up @@ -89,43 +90,18 @@ export default withBundle(
source: '/legacy/:slug*',
destination: `${archiveServerHostname}/:slug*`,
},
].filter((e) => e)
]
},
async headers() {
return [
{
source: '/:path*',
headers: securityHeaders,
},
].filter((e) => e)
]
},
async redirects() {
return [
// Redirect IE users to not-supported page
{
source: '/',
has: [
{
type: 'header',
key: 'user-agent',
value: '.*(MSIE|Trident).*',
},
],
permanent: true,
destination: '/not-supported.html',
},
// redirects for /50 site
['global', 'global-development', 'global-test'].includes(dataset) && {
source: '/50/en/:slug*',
destination: '/magazine',
permanent: true,
},
['global', 'global-development', 'global-test'].includes(dataset) && {
source: '/50/:slug*',
destination: '/no/magasin',
permanent: true,
},
].filter((e) => e)
return await getAllRedirects()
},
}),
)
22 changes: 21 additions & 1 deletion web/pages/[[...slug]].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ import { defaultLanguage } from '../languages'
import Header from '../pageComponents/shared/Header'
import { FormattedMessage } from 'react-intl'
import getIntl from '../common/helpers/getIntl'
import { getStaticBuildRoutePaths } from '../common/helpers/getPaths'
import { getStaticBuildRoutePaths, pathExistsInSanity } from '../common/helpers/getPaths'
import getPageSlugs from '../common/helpers/getPageSlugs'
import { getComponentsData } from '../lib/fetchData'
import { useContext, useEffect } from 'react'
import { PreviewContext } from '../lib/contexts/PreviewContext'
import archivedNews from '../lib/archive/archivedNewsPaths.json'
import { Flags } from '../common/helpers/datasetHelpers'

const MagazinePage = dynamic(() => import('../pageComponents/pageTemplates/MagazinePage'))
const LandingPage = dynamic(() => import('../pageComponents/pageTemplates/LandingPage'))
Expand Down Expand Up @@ -97,6 +99,24 @@ export const getStaticProps: GetStaticProps = async ({ params, preview = false,
const { query, queryParams } = await getQueryFromSlug(params?.slug as string[], locale)
const intl = await getIntl(locale, preview)

// http://localhost:3000/news/2002/12/16/AlphaNorthContracts
if (queryParams?.slug && queryParams.slug.includes('news') && Flags.HAS_ARCHIVED_NEWS) {
const existsInSanity = await pathExistsInSanity(queryParams.slug, preview)
if (!existsInSanity) {
const archivedPath = queryParams.slug.replace('news', 'news/archive')
const slug = archivedNews.find((e: { slug: string }) => e.slug.toLowerCase() === archivedPath)?.slug
return slug
? {
redirect: {
permanent: true,
destination: slug,
},
props: {},
}
: { notFound: true }
}
}

const { menuData, pageData, footerData } = await getComponentsData(
{
query,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const OldArchivedNewsPage = ({ data }: OldArchivedNewsPageProps): JSX.Element =>
scriptTag.id = 'legacyScript'
document.body.appendChild(scriptTag)
}
})
}, [isArchivePage])

if (!router.isFallback && !data?.news) {
setIsArchivePage(false)
Expand Down Expand Up @@ -215,12 +215,15 @@ export const getStaticProps: GetStaticProps = async ({ preview = false, params,
const pagePathArray = params?.pagePath as string[]
const pagePath = pagePathArray.join('/')

const archivedItems = archivedNews.filter((e) => e.slug === `/news/archive/${pagePath}`)
const archivedItems = archivedNews.filter((e) => e.slug.toLowerCase() === `/news/archive/${pagePath}`)

if (archivedItems.length === 0) return { notFound: true }

const response = await fetchArchiveData(pagePathArray, pagePath, locale)
const cammelCasedPath = archivedItems[0].slug.replace('/news/archive/', '')

const response = await fetchArchiveData(pagePathArray, cammelCasedPath, locale)

if (response.status === 404) return fallbackToAnotherLanguage(pagePathArray, pagePath, locale)
if (response.status === 404) return fallbackToAnotherLanguage(pagePathArray, cammelCasedPath, locale)

const pageData = await parseResponse(response)
const menuQuery = Flags.HAS_FANCY_MENU ? globalMenuQuery : simpleMenuQuery
Expand Down
2 changes: 0 additions & 2 deletions web/pages/nyheter/index.global.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,11 @@ export const getServerSideProps: GetServerSideProps = async ({ req, preview = fa
// We will also return 404 if the locale is not Norwegian.
// This is a hack, and we should improve this at some point
// See https://github.com/vercel/next.js/discussions/18485

if (locale !== 'no') {
return {
notFound: true,
}
}

const lang = getNameFromLocale(locale)
const intl = await getIntl(locale, false)

Expand Down
Loading

0 comments on commit 31026fe

Please sign in to comment.