Skip to content

Commit

Permalink
Merge pull request #332 from teamleadercrm/cache-proxy-values
Browse files Browse the repository at this point in the history
Cache the values that are created by the proxy
  • Loading branch information
lowiebenoot authored Aug 30, 2022
2 parents 24f20d4 + 04d93c5 commit 8f69002
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

### Changed

- Cache the values that are created by the proxy. So if you call an endpoint 2 times, it will call the same function 2 times. This makes testing easier. ([@lowiebenoot](https://github.com/lowiebenoot) in [#332](https://github.com/teamleadercrm/sdk-js/pull/332))

### Deprecated

### Removed
Expand Down
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 8f69002

Please sign in to comment.