Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MWPW-133754 - Support structured data API for SEO #1115

Merged
merged 8 commits into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion libs/features/seotech/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# SEOTECH

Collection of SEO-related features that use the SEOTECH service.
For more details see [SEOTECH API](https://wiki.corp.adobe.com/display/seoteam/SEOTECH+API) (Corp Only).
See [structured-data](https://milo.adobe.com/docs/authoring/structured-data) for authoring documentation including examples.
See [SEOTECH Wiki](https://wiki.corp.adobe.com/display/seoteam/SEOTECH) for documentation regarding the service.

## Video

Expand All @@ -19,3 +20,17 @@ Video Platforms:
- BYO HTML5: TBD

See [video-metadata](../../blocks/video-metadata/) if you need to define a specific VideoObject on your page.

## Structured Data

This feature queries the SEOTECH service for structured data that should be added to the page.

Metadata Properties:

- `seotech-structured-data`: `on` to enable SEOTECH lookup
- `seotech-sheet-url`: url of Franklin Spreadsheet JSON (Optional)

You can also specify `seotech-sheet-url` as a query parameter.
Otherwise SEOTECH will search for _/structured-data.json_ at the root of the current page.

See [seotech page](https://git.corp.adobe.com/pages/wcms/seotech/) (Corp Only) for list of supported structured data types.
41 changes: 36 additions & 5 deletions libs/features/seotech/seotech.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,45 @@ export async function getVideoObject(url, seotechAPIUrl) {
return body.videoObject;
}

export default async function appendVideoObjectScriptTag(url, { createTag, getConfig }) {
export async function getStructuredData(url, sheetUrl, seotechAPIUrl) {
const apiUrl = new URL(seotechAPIUrl);
apiUrl.pathname = '/api/v1/web/seotech/getStructuredData';
apiUrl.searchParams.set('url', url);
if (sheetUrl) {
apiUrl.searchParams.set('sheetUrl', sheetUrl);
}
const resp = await fetch(apiUrl.href, { headers: { 'Content-Type': 'application/json' } });
const body = await resp?.json();
if (!resp.ok) {
throw new Error(`Failed to fetch structured data: ${body?.error}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this also contain the sheetUrl so the Splunk messages are clear as to which sheet failed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sheetUrl is used by the service, so if there is a problem with it then the URL should be returned in body.error msg. Will fix api to do this.

}
return body.objects;
}

export async function appendScriptTag({ locationUrl, getMetadata, createTag, getConfig }) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just import getMetadata, createTag, getConfig

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is convention of similar features as it prevents import cycle. It also makes testing a little easier

const windowUrl = new URL(locationUrl);
const seotechAPIUrl = getConfig()?.env?.name === 'prod'
? SEOTECH_API_URL_PROD : SEOTECH_API_URL_STAGE;
try {
const obj = await getVideoObject(url, seotechAPIUrl);

const append = (obj) => {
const script = createTag('script', { type: 'application/ld+json' }, JSON.stringify(obj));
document.head.append(script);
} catch (e) {
logError(e.message);
};

const promises = [];
if (getMetadata('seotech-structured-data') === 'on') {
const pageUrl = `${windowUrl.origin}${windowUrl.pathname}`;
const sheetUrl = (new URLSearchParams(windowUrl.search)).get('seotech-sheet-url') || getMetadata('seotech-sheet-url');
promises.push(getStructuredData(pageUrl, sheetUrl, seotechAPIUrl)
.then((objects) => objects.forEach((obj) => append(obj)))
.catch((e) => logError(e.message)));
}
if (getMetadata('seotech-video-url')) {
promises.push(getVideoObject(getMetadata('seotech-video-url'), seotechAPIUrl)
.then((videoObject) => append(videoObject))
.catch((e) => logError(e.message)));
}
return Promise.all(promises);
}

export default appendScriptTag;
7 changes: 4 additions & 3 deletions libs/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -890,9 +890,10 @@ export async function loadArea(area = document) {
if (appendage) {
import('../features/title-append/title-append.js').then((module) => module.default(appendage));
}
const seotechVideoUrl = getMetadata('seotech-video-url');
if (seotechVideoUrl) {
import('../features/seotech/seotech.js').then((module) => module.default(seotechVideoUrl, { createTag, getConfig }));
if (getMetadata('seotech-structured-data') === 'on' || getMetadata('seotech-video-url')) {
import('../features/seotech/seotech.js').then((module) => module.default(
{ locationUrl: window.location.href, getMetadata, createTag, getConfig },
));
}
const richResults = getMetadata('richresults');
if (richResults) {
Expand Down
78 changes: 73 additions & 5 deletions test/features/seotech/seotech.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,64 @@ import { stub } from 'sinon';
import { waitForElement } from '../../helpers/waitfor.js';

import { getConfig, createTag } from '../../../libs/utils/utils.js';
import appendVideoObjectScriptTag from '../../../libs/features/seotech/seotech.js';
import { appendScriptTag } from '../../../libs/features/seotech/seotech.js';

describe('seotech', () => {
describe('appendVideoObjectScriptTag', () => {
describe('appendScriptTag + seotech-structured-data', () => {
beforeEach(async () => {
window.lana = { log: (s) => console.log(`LANA NOT STUBBED! ${s}`) };
});
afterEach(() => {
window.fetch?.restore?.();
window.lana?.restore?.();
});

it('should not append JSON-LD', async () => {
const lanaStub = stub(window.lana, 'log');
const getMetadata = stub().returns(null);
getMetadata.withArgs('seotech-structured-data').returns('on');
const fetchStub = stub(window, 'fetch');
fetchStub.returns(Promise.resolve(Response.json(
{ error: 'ERROR!' },
{ status: 400 },
)));
await appendScriptTag(
{ locationUrl: window.location.href, getMetadata, getConfig, createTag },
);
const expectedApiCall = 'https://14257-seotech-stage.adobeioruntime.net/api/v1/web/seotech/getStructuredData?url=http%3A%2F%2Flocalhost%3A2000%2F';
expect(fetchStub.getCall(0).firstArg).to.equal(expectedApiCall);
expect(lanaStub.getCall(0).firstArg).to.equal('SEOTECH: Failed to fetch structured data: ERROR!');
});

it('should append JSON-LD', async () => {
const locationUrl = 'http://localhost:2000/?seotech-sheet-url=http://foo';
const lanaStub = stub(window.lana, 'log');
const fetchStub = stub(window, 'fetch');
const getConfigStub = stub().returns({ env: { name: 'prod' } });
const getMetadata = stub().returns(null);
getMetadata.withArgs('seotech-structured-data').returns('on');
const expectedObject = {
'@context': 'http://schema.org',
'@type': 'VideoObject',
name: 'fake',
};
fetchStub.returns(Promise.resolve(Response.json(
{ objects: [expectedObject] },
{ status: 200 },
)));
await appendScriptTag(
{ locationUrl, getMetadata, getConfig: getConfigStub, createTag },
);
const expectedApiCall = 'https://14257-seotech.adobeioruntime.net/api/v1/web/seotech/getStructuredData?url=http%3A%2F%2Flocalhost%3A2000%2F&sheetUrl=http%3A%2F%2Ffoo';
expect(fetchStub.getCall(0).firstArg).to.equal(expectedApiCall);
const el = await waitForElement('script[type="application/ld+json"]');
const obj = JSON.parse(el.text);
expect(obj).to.deep.equal(expectedObject);
expect(lanaStub.called).to.be.false;
});
});

describe('appendScriptTag + seotech-video-url', () => {
beforeEach(async () => {
window.lana = { log: () => console.log('LANA NOT STUBBED!') };
});
Expand All @@ -17,26 +71,37 @@ describe('seotech', () => {

it('should not append JSON-LD if url is invalid', async () => {
const lanaStub = stub(window.lana, 'log');
await appendVideoObjectScriptTag('', { getConfig, createTag });
const getMetadata = stub().returns(null);
getMetadata.withArgs('seotech-video-url').returns('fake');
await appendScriptTag(
{ locationUrl: window.location.href, getMetadata, getConfig, createTag },
);
expect(lanaStub.calledOnceWith('SEOTECH: Failed to construct \'URL\': Invalid URL')).to.be.true;
});

it('should not append JSON-LD if url not found', async () => {
const lanaStub = stub(window.lana, 'log');
const getMetadata = stub().returns(null);
getMetadata.withArgs('seotech-video-url').returns('http://fake');
const fetchStub = stub(window, 'fetch');
fetchStub.returns(Promise.resolve(Response.json(
{ error: 'ERROR!' },
{ status: 400 },
)));
await appendVideoObjectScriptTag('http://fake', { getConfig, createTag });
await appendScriptTag(
{ locationUrl: window.location.href, getMetadata, getConfig, createTag },
);
expect(fetchStub.calledOnceWith(
'https://14257-seotech-stage.adobeioruntime.net/api/v1/web/seotech/getVideoObject?url=http://fake/',
)).to.be.true;
expect(lanaStub.calledOnceWith('SEOTECH: Failed to fetch video: ERROR!')).to.be.true;
});

it('should append JSON-LD', async () => {
const lanaStub = stub(window.lana, 'log');
const fetchStub = stub(window, 'fetch');
const getMetadata = stub().returns(null);
getMetadata.withArgs('seotech-video-url').returns('http://fake');
const expectedVideoObject = {
'@context': 'http://schema.org',
'@type': 'VideoObject',
Expand All @@ -46,13 +111,16 @@ describe('seotech', () => {
{ videoObject: expectedVideoObject },
{ status: 200 },
)));
await appendVideoObjectScriptTag('http://fake', { getConfig, createTag });
await appendScriptTag(
{ locationUrl: window.location.href, getMetadata, getConfig, createTag },
);
expect(fetchStub.calledOnceWith(
'https://14257-seotech-stage.adobeioruntime.net/api/v1/web/seotech/getVideoObject?url=http://fake/',
)).to.be.true;
const el = await waitForElement('script[type="application/ld+json"]');
const obj = JSON.parse(el.text);
expect(obj).to.deep.equal(expectedVideoObject);
expect(lanaStub.called).to.be.false;
});
});
});