Skip to content

Commit

Permalink
✨ cache the values that are created by the proxy
Browse files Browse the repository at this point in the history
This way if you call the same endpoint 2 times, it will also call the same function 2 times. This is a bit easier when implementing tests and you expect a certain function to be called.
  • Loading branch information
lowiebenoot committed Aug 30, 2022
1 parent 24f20d4 commit 7e53607
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
12 changes: 12 additions & 0 deletions src/__tests__/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,16 @@ describe('fetch response handling', () => {
const data = await api.contacts.info({ userId: '84989' }, { plugins: { response: [normalize] } });
expect(data).toEqual({ contacts: { 84845512: { id: '84845512', lastName: 'doe', name: 'john' } } });
});

it('using the same endpoint twice actually uses the same function', async () => {
const getAccessToken = () => 'thisisatoken';

const api = API({
getAccessToken,
});

expect(api.contacts.info).toEqual(api.contacts.info);
expect(api.companies.info).toEqual(api.companies.info);
expect(api.companies.info).not.toEqual(api.contacts.info);
});
});
23 changes: 19 additions & 4 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,38 @@ type ActionEndpoint = <T = any>(
) => Promise<T>;

const API = (globalConfiguration: GlobalConfiguration) => {
const cachedActionEndpoints: Record<string, Record<string, ActionEndpoint>> = {};

return new Proxy<Record<string, Record<string, ActionEndpoint>>>(
{},
{
get(_target, domainName) {
get(_target, domainNameKey) {
return new Proxy(
{},
{
get(_target, actionName) {
get(_target, actionNameKey) {
const domainName = String(domainNameKey);
const actionName = String(actionNameKey);

if (typeof cachedActionEndpoints[domainName] === 'undefined') {
cachedActionEndpoints[domainName] = {};
}

if (typeof cachedActionEndpoints[domainName][actionName] !== 'undefined') {
return cachedActionEndpoints[domainName][actionName];
}

const actionEndpoint: ActionEndpoint = async (parameters = {}, localConfiguration = {}) => {
const configuration = mergeConfigurations({ globalConfiguration, localConfiguration });
return request({
domainName: String(domainName),
actionName: String(actionName),
domainName,
actionName,
parameters,
configuration,
});
};

cachedActionEndpoints[domainName][actionName] = actionEndpoint;
return actionEndpoint;
},
},
Expand Down

0 comments on commit 7e53607

Please sign in to comment.