Skip to content
Open
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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,13 @@ app.get('/api/opengraph', async (req, res) => {
Add your own authentication and rate limiting to this endpoint; otherwise it
just moves the open quota from your key to your server.

### How many requests a card makes
Cards that ask for the same site with the same options share one request, and a
successful answer is reused for 60 seconds. Showing one link several times on a
page, or re-mounting a card, therefore costs one API request, not one per mount.
A request is cancelled when the last card waiting for it leaves the page.
`forceCacheUpdate` always makes a new request.

## OpenGraph.io API Parameters
### Below is a list of parameters and their descriptions, which can be passed to the OpenGraph.io API through the opengraph-react component.

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "opengraph-react",
"version": "2.4.2",
"version": "2.5.1",
"description": "Handy React components for www.opengraph.io",
"main": "build/index.js",
"files": [
Expand Down
111 changes: 111 additions & 0 deletions src/__tests__/components.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import LinkedInComponent from '../components/linkedIn';
import ErrorBoundary from '../components/error';
import { getProductInfo } from '../util/getProductInfo';
import { buildRequestUrl } from '../util/buildRequestUrl';
import { requestResults, clearResultsCache } from '../util/requestResults';

const ogResponse = {
openGraph: { title: 'Example', url: 'https://example.com/', image: { url: 'https://example.com/og.png' } },
Expand All @@ -20,6 +21,7 @@ const mockFetch = (body) => {

afterEach(() => {
delete global.fetch;
clearResultsCache();
});

describe('default fetch path', () => {
Expand Down Expand Up @@ -99,3 +101,112 @@ describe('video iframe', () => {
}
});
});

// OGR-005 follow-up (#46): every mount used to issue its own request, with no
// way to stop one whose card had already left the page. In direct mode each of
// those requests spends the site's API key from a visitor's browser.
describe('request sharing', () => {
const tick = () => new Promise((resolve) => setTimeout(resolve, 0));

it('makes one request when the same card is mounted several times', async () => {
const fetchMock = mockFetch(ogResponse);
const { container } = render(
<div>
<OpenGraphReactComponent site="https://example.com" appId="abc" />
<OpenGraphReactComponent site="https://example.com" appId="abc" />
<OpenGraphReactComponent site="https://example.com" appId="abc" component="small" />
</div>
);

await waitFor(() => expect(container.querySelectorAll('img').length).toBeGreaterThanOrEqual(2));
expect(fetchMock).toHaveBeenCalledTimes(1);
});

it('makes one request under React.StrictMode', async () => {
const fetchMock = mockFetch(ogResponse);
const { container } = render(
<React.StrictMode>
<OpenGraphReactComponent site="https://example.com" appId="abc" />
</React.StrictMode>
);

await waitFor(() => expect(container.querySelector('.wrapperLarge')).not.toBeNull());
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(false);
});

it('reuses a recent answer for a later mount, and asks again for a different site', async () => {
const fetchMock = mockFetch(ogResponse);
const first = render(<OpenGraphReactComponent site="https://example.com" appId="abc" />);
await waitFor(() => expect(first.container.querySelector('.wrapperLarge')).not.toBeNull());
first.unmount();

const second = render(<OpenGraphReactComponent site="https://example.com" appId="abc" />);
await waitFor(() => expect(second.container.querySelector('.wrapperLarge')).not.toBeNull());
expect(fetchMock).toHaveBeenCalledTimes(1);

const third = render(<OpenGraphReactComponent site="https://example.org" appId="abc" />);
expect(fetchMock).toHaveBeenCalledTimes(2);
await waitFor(() => expect(third.container.querySelector('.wrapperLarge')).not.toBeNull());
});

it('always asks again when forceCacheUpdate is set', async () => {
const fetchMock = mockFetch(ogResponse);
const first = render(<OpenGraphReactComponent site="https://example.com" appId="abc" forceCacheUpdate />);
await waitFor(() => expect(first.container.querySelector('.wrapperLarge')).not.toBeNull());
first.unmount();

const second = render(<OpenGraphReactComponent site="https://example.com" appId="abc" forceCacheUpdate />);
expect(fetchMock).toHaveBeenCalledTimes(2);
await waitFor(() => expect(second.container.querySelector('.wrapperLarge')).not.toBeNull());
});

it('aborts a request once the only card waiting for it unmounts', async () => {
global.fetch = jest.fn(() => new Promise(() => {}));
const { unmount } = render(<OpenGraphReactComponent site="https://example.com" appId="abc" />);
const { signal } = global.fetch.mock.calls[0][1];
expect(signal.aborted).toBe(false);

unmount();
await tick();
expect(signal.aborted).toBe(true);
});

it('keeps a shared request alive while another card still waits for it', async () => {
global.fetch = jest.fn(() => new Promise(() => {}));
const first = render(<OpenGraphReactComponent site="https://example.com" appId="abc" />);
render(<OpenGraphReactComponent site="https://example.com" appId="abc" />);
expect(global.fetch).toHaveBeenCalledTimes(1);

first.unmount();
await tick();
expect(global.fetch.mock.calls[0][1].signal.aborted).toBe(false);
});

it('does not remember an error response or a failed request', async () => {
mockFetch({ error: { code: 101, message: 'Invalid API key' } });
await requestResults('https://opengraph.io/api/1.1/site/x?app_id=bad').promise;
mockFetch(ogResponse);
const body = await requestResults('https://opengraph.io/api/1.1/site/x?app_id=bad').promise;
expect(body).toEqual(ogResponse);

global.fetch = jest.fn(() => Promise.reject(new Error('offline')));
await expect(requestResults('https://opengraph.io/api/1.1/site/y').promise).rejects.toThrow('offline');
mockFetch(ogResponse);
await expect(requestResults('https://opengraph.io/api/1.1/site/y').promise).resolves.toEqual(ogResponse);
});

it('does not update a card after it unmounted', async () => {
let resolveFetch;
global.fetch = jest.fn(() => new Promise((resolve) => { resolveFetch = resolve; }));
const errors = jest.spyOn(console, 'error').mockImplementation(() => {});
const keep = render(<OpenGraphReactComponent site="https://example.com" appId="abc" />);
const gone = render(<OpenGraphReactComponent site="https://example.com" appId="abc" />);

gone.unmount();
resolveFetch({ json: () => Promise.resolve(ogResponse) });
await waitFor(() => expect(keep.container.querySelector('.wrapperLarge')).not.toBeNull());
expect(errors).not.toHaveBeenCalled();
errors.mockRestore();
});
});
51 changes: 32 additions & 19 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import RenderSmall from './components/small';

import { getResultsToUse } from './util/getResultsToUse';
import { buildRequestUrl } from './util/buildRequestUrl';
import { requestResults } from './util/requestResults';
import ErrorBoundary from './components/error';
import XComponent from './components/x';
import FacebookComponent from './components/facebook';
Expand All @@ -27,29 +28,41 @@ const OpenGraphReactComponent = (props) => {


React.useEffect(() => {
const fetchResults = async (url) => {
try {
const response = await fetch(url);
const result = await response.json();
if (result.error) {
setError(result.error);
if (dontMakeCall) {
setResult(getResultsToUse(results));
return undefined;
}

const url = buildRequestUrl({
site, appId, proxyUrl, acceptLang,
useProxy, forceCacheUpdate, fullRender,
usePremium, useSuperior, disableAutoProxy,
});

// Identical requests are shared, and a request nobody is waiting for any
// more is aborted, so mounting the same card many times (a list, a
// re-render, StrictMode) costs one API request instead of one per mount.
let active = true;
const request = requestResults(url, { skipCache: Boolean(forceCacheUpdate) });

request.promise.then(
(body) => {
if (!active) return;
if (body && body.error) {
setError(body.error);
} else {
setResult(prev => ({ ...prev, ...result }));
setResult(prev => ({ ...prev, ...body }));
}
} catch (error) {
setError(error);
},
(err) => {
if (active) setError(err);
}
}
);

if (dontMakeCall) {
setResult(getResultsToUse(results));
} else {
fetchResults(buildRequestUrl({
site, appId, proxyUrl, acceptLang,
useProxy, forceCacheUpdate, fullRender,
usePremium, useSuperior, disableAutoProxy,
}));
}
return () => {
active = false;
request.release();
};
}, [ ]);

// The fetch path only ever filled `result`, so cards got a null
Expand Down
85 changes: 85 additions & 0 deletions src/util/requestResults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// How long a successful response is reused. Short on purpose: it is there to
// collapse the burst of identical requests a page makes while it renders
// (several cards for one URL, a list re-mounting, React StrictMode's double
// mount), not to act as a long-lived cache.
const DEFAULT_TTL_MS = 60 * 1000;
const MAX_ENTRIES = 100;

// url -> { promise, controller, subscribers, settled, expires }
const entries = new Map();

const forget = (url, entry) => {
if (entries.get(url) === entry) entries.delete(url);
};

const startRequest = (url, ttlMs) => {
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
const entry = { controller, subscribers: 0, settled: false, expires: 0 };

entry.promise = fetch(url, controller ? { signal: controller.signal } : undefined)
.then((response) => response.json())
.then(
(body) => {
entry.settled = true;
entry.expires = Date.now() + ttlMs;
// An error body (bad key, quota, unreachable site) is not worth
// remembering: the next mount should ask again.
if (!body || body.error) forget(url, entry);
return body;
},
(err) => {
entry.settled = true;
forget(url, entry);
throw err;
}
);
// Every subscriber may have gone by the time this settles.
entry.promise.catch(() => {});

if (entries.size >= MAX_ENTRIES) {
entries.delete(entries.keys().next().value);
}
entries.set(url, entry);
return entry;
};

/**
* Ask for an API response, sharing one network request between every caller
* that wants the same URL at the same time or shortly after.
*
* Returns the shared promise and a `release` function. Call `release` when the
* caller no longer wants the answer (the component unmounted): once nobody is
* waiting, the request is aborted instead of running on and spending a
* request against the API key for a card that is no longer on the page.
*/
export const requestResults = (url, { skipCache = false, ttlMs = DEFAULT_TTL_MS } = {}) => {
let entry = entries.get(url);
const fresh = entry && (!entry.settled || entry.expires > Date.now());
if (!fresh || skipCache) {
entry = startRequest(url, ttlMs);
}

entry.subscribers += 1;
let released = false;

return {
promise: entry.promise,
release: () => {
if (released) return;
released = true;
entry.subscribers -= 1;
// Decided on the next tick, not now: React StrictMode (and a keyed
// re-render) unmounts and remounts straight away, and the remount should
// pick this request up rather than abort it and start a second one.
setTimeout(() => {
if (!entry.settled && entry.subscribers === 0) {
forget(url, entry);
if (entry.controller) entry.controller.abort();
}
}, 0);
},
};
};

/** Drop every remembered response. */
export const clearResultsCache = () => entries.clear();
2 changes: 2 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const path = require('path');

module.exports = {
mode: 'production',
// Ship a source map so consumers can read what the published bundle was built from.
devtool: 'source-map',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
Expand Down
Loading