Skip to content

Commit

Permalink
- Provide a flexible mechanism for key-based lookup with fallback opt…
Browse files Browse the repository at this point in the history
…ions in support of content updates related to ASL-4413

- Include tests to validate that the snippet component can correctly handle fallbacks when attempting to retrieve templates
  • Loading branch information
edemirbag committed Mar 20, 2024
1 parent b06fc6f commit 6310ed8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/snippet/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,27 @@ import { connect } from 'react-redux';
import Markdown from '../markdown';
import { render } from 'mustache';

function getTemplate(content, primary, fallback) {
const keysToTry = [primary, ...(Array.isArray(fallback) ? fallback : [fallback])];

for (let key of keysToTry) {
const template = get(content, key);
if (template != undefined) {
return template;
}
}

return undefined;
}

export const Snippet = ({ content, children, optional, fallback, ...props }) => {
const str = get(content, children, get(content, fallback));
const str = getTemplate(content, children, fallback);
if (str === undefined && optional) {
return null;

}
if (str === undefined) {
throw new Error(`Failed to lookup content snippet: ${children}`);
return `Failed to lookup content snippet: ${children}`;
}
if (typeof str !== 'string') {
throw new Error(`Invalid content snippet for key ${children}: ${JSON.stringify(str)}`);
Expand Down
12 changes: 12 additions & 0 deletions src/snippet/index.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,16 @@ two`
expect(wrapper.html()).toEqual(paragraphs);
});

test('can accept single fallback', () => {
const wrapper = render(<div><Snippet content={content} fallback={'paragraphs'}>non.existent</Snippet></div>);
expect(wrapper.find('p').length).toEqual(2);
expect(wrapper.html()).toEqual(paragraphs);
});

test('can accept multiple fallbacks', () => {
const wrapper = render(<div><Snippet content={content} fallback={['non.existent.2', 'paragraphs', 'list']}>non.existent</Snippet></div>);
expect(wrapper.find('p').length).toEqual(2);
expect(wrapper.html()).toEqual(paragraphs);
});

});

0 comments on commit 6310ed8

Please sign in to comment.