Skip to content

Commit

Permalink
Merge pull request #866 from dpc-sdp/bugfix/section-tags
Browse files Browse the repository at this point in the history
Set section-cache-tags respone header for pages
  • Loading branch information
jeffdowdle authored Sep 25, 2023
2 parents 982060d + 57c92cd commit 0844c36
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 31 deletions.
12 changes: 12 additions & 0 deletions packages/nuxt-ripple/composables/use-tide-page.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { TidePageBase } from './../types'
import { appendResponseHeader } from 'h3'
import { useCookie, isPreviewPath, AuthCookieNames } from '#imports'

const isCacheTimeExpired = (date: number, expiryInMinutes = 5) => {
Expand All @@ -14,6 +15,7 @@ export const useTidePage = async (
): Promise<TidePageBase> => {
const route = useRoute()
const path = slug || route.path
const event = useRequestEvent()
const { public: config } = useRuntimeConfig()
const siteId = site || config.tide?.site

Expand Down Expand Up @@ -49,6 +51,8 @@ export const useTidePage = async (
headers.cookie = `${AuthCookieNames.ACCESS_TOKEN}=${accessTokenCookie.value};`
}

let sectionCacheTags

if (!pageData.value) {
const { data, error } = await useFetch('/api/tide/page', {
key: `page-${path}`,
Expand All @@ -59,11 +63,19 @@ export const useTidePage = async (
},
headers,
async onResponse({ response }) {
sectionCacheTags = response.headers.get('section-cache-tags')

if (response.ok && response._data) {
response._data['_fetched'] = Date.now()
}
}
})

// Section.io cache tags must be set on the response header to invalidate the cache after a change in drupal
if (sectionCacheTags) {
appendResponseHeader(event, 'section-cache-tags', sectionCacheTags)
}

if (error && error.value?.statusCode) {
useTideError(error.value?.statusCode)
}
Expand Down
24 changes: 22 additions & 2 deletions packages/nuxt-ripple/server/api/tide/page.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
//@ts-nocheck runtime imports
import { defineEventHandler, getQuery, H3Event, getCookie } from 'h3'
import {
defineEventHandler,
getQuery,
H3Event,
getCookie,
setResponseHeader
} from 'h3'
import { createHandler, TidePageApi } from '@dpc-sdp/ripple-tide-api'
import { BadRequestError } from '@dpc-sdp/ripple-tide-api/errors'
import { useNitroApp } from '#imports'
Expand Down Expand Up @@ -31,7 +37,21 @@ export const createPageHandler = async (
headers['X-OAuth2-Authorization'] = `Bearer ${tokenCookie}`
}

return await tidePageApi.getPageByPath(query.path, query.site, {}, headers)
const pageResponse = await tidePageApi.getPageByPath(
query.path,
query.site,
{},
headers
)

// Need to pass on the section cache tags to the nuxt app
setResponseHeader(
event,
'section-cache-tags',
pageResponse.headers['section-cache-tags']
)

return pageResponse.data
})
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,18 @@ describe('TideApiBase', () => {
mockLogger
)
it('should call http client get method', async () => {
mockClient.onGet(`${exampleApiConfig.apiPrefix}/site`).reply(200, {
field: 'test'
})
mockClient.onGet(`${exampleApiConfig.apiPrefix}/site`).reply(
200,
{
field: 'test'
},
{
testHeader: 'test123'
}
)
const result = await tideApiBase.get('/site')
expect(result).toEqual({ field: 'test' })
expect(result.data).toEqual({ field: 'test' })
expect(result.headers.testHeader).toEqual('test123')
mockClient.reset()
})
})
Expand Down
4 changes: 2 additions & 2 deletions packages/ripple-tide-api/src/services/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ export default class HttpClient {

_initializeResponseInterceptor() {
this.client.interceptors.response.use(
({ data }) => {
return data
(response) => {
return response
},
(error) => {
if (axios.isAxiosError(error)) {
Expand Down
16 changes: 10 additions & 6 deletions packages/ripple-tide-api/src/services/tide-api-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default class TideApiBase extends HttpClient {
return await this.getMappedDataAux(mapping, resource)
}

async get(url: string, config = {}): Promise<any> {
async get(url: string, config = {}): Promise<{ data: any; headers: any }> {
try {
return await this.client.get(url, { ...config })
} catch (error) {
Expand Down Expand Up @@ -93,9 +93,12 @@ export default class TideApiBase extends HttpClient {
}

try {
const menusResponse = await this.get(`/menu_items/${menuName}`, {
params
})
const { data: menusResponse } = await this.get(
`/menu_items/${menuName}`,
{
params
}
)

if (menusResponse?.data) {
return getHierarchicalMenu(menusResponse.data, activePath)
Expand Down Expand Up @@ -128,7 +131,7 @@ export default class TideApiBase extends HttpClient {

async getAllPaginatedMenuLinks(siteId, menuName) {
// Get the first page of links, this will also give us a link to the next page
let response = await this.get(
let { data: response } = await this.get(
'/menu_link_content/menu_link_content?site=' + siteId,
{
params: {
Expand All @@ -152,7 +155,8 @@ export default class TideApiBase extends HttpClient {

// Get the rest of the menu links by following their 'next' link until a response has no next link
while (response?.links?.next) {
response = await this.get(response.links.next.href)
const { data: nextResponse } = await this.get(response.links.next.href)
response = nextResponse
menuLinks = [...menuLinks, ...response.data]
}

Expand Down
41 changes: 28 additions & 13 deletions packages/ripple-tide-api/src/services/tide-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,9 @@ export default class TidePageApi extends TideApiBase {
this.path = path

const routeUrl = `/route?site=${site}&path=${path}`

return this.get(routeUrl)
.then((response) => response?.data?.attributes)
.then((response) => response?.data?.data?.attributes)
.catch((error) => {
throw new NotFoundError(
`Route for site "${site}" and path "${path}" not found`,
Expand Down Expand Up @@ -137,7 +138,7 @@ export default class TidePageApi extends TideApiBase {
}

async getPageByShareLink(path: string, site: string) {
const response = await this.get(path).then((res) => {
const response = await this.get(path).then(({ data: res }) => {
return res?.data ? jsonapiParse.parse(res).data || res.data : null
})

Expand Down Expand Up @@ -249,12 +250,20 @@ export default class TidePageApi extends TideApiBase {
this.sectionId = route.section

const nodeUrl = `/${route.entity_type}/${route.bundle}/${route.uuid}`
return await this.get(nodeUrl, config).then((response) => {
if (response.data) {
const data = jsonapiParse.parse(response).data || response.data
return this.getTidePage(data, route)

return await this.get(nodeUrl, config).then(({ data, headers }) => {
if (data.data) {
const parsedData = jsonapiParse.parse(data).data || data.data
return {
data: this.getTidePage(parsedData, route),
headers
}
}

return {
data,
headers
}
return response
})
}
throw new Error('Invalid route')
Expand Down Expand Up @@ -286,7 +295,7 @@ export default class TidePageApi extends TideApiBase {
}

try {
const response = await this.get(`/node/${type}`, {
const { data: response } = await this.get(`/node/${type}`, {
params
})
if (response) {
Expand Down Expand Up @@ -329,7 +338,9 @@ export default class TidePageApi extends TideApiBase {
}
try {
// Give more time for list response, normally it's slow
const response = await this.get(`${entityType}/${bundle}`, { params })
const { data: response } = await this.get(`${entityType}/${bundle}`, {
params
})

if (allPages) {
const allPagesData = await this.getAllPaginatedData(response)
Expand Down Expand Up @@ -365,10 +376,11 @@ export default class TidePageApi extends TideApiBase {

// Use getByURL directly here because resource url contains all query params.
try {
response = await this.get(resource, {
const { data: nextResponse } = await this.get(resource, {
headers: headersConfig,
site: this.site
})
response = nextResponse
const nextData = parse
? jsonapiParse.parse(response).data
: response.data
Expand Down Expand Up @@ -418,9 +430,12 @@ export default class TidePageApi extends TideApiBase {
site: this.site
}
try {
const response = await this.get(`/taxonomy_term/${taxonomyName}`, {
params
})
const { data: response } = await this.get(
`/taxonomy_term/${taxonomyName}`,
{
params
}
)
if (response) {
const resource = jsonapiParse.parse(response).data
return resource
Expand Down
4 changes: 3 additions & 1 deletion packages/ripple-tide-api/src/services/tide-site.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ export default class TideSite extends TideApiBase {
}
}
try {
const response = await this.get(`/taxonomy_term/sites`, { params })
const { data: response } = await this.get(`/taxonomy_term/sites`, {
params
})
if (response && response.data.length > 0) {
const resource = jsonapiParse.parse(response).data[0]
const siteData = await this.getMappedData(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,12 @@ class TidePublicationIndexApi extends TideApiBase {

async getPublicationMenu(id: string) {
try {
const response = await this.get(`/node/publication/${id}/hierarchy`, {
params: { site: this.siteId }
})
const { data: response } = await this.get(
`/node/publication/${id}/hierarchy`,
{
params: { site: this.siteId }
}
)
const resource = jsonapiParse.parse(response).data.meta.hierarchy
const siteData = await this.getMappedData(
this.publicationMapping.mapping,
Expand Down

0 comments on commit 0844c36

Please sign in to comment.