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

Remove deprecated functionality #296

Merged
merged 3 commits into from
Sep 3, 2024
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
2 changes: 2 additions & 0 deletions src/api/fetchContent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {JsonObject, JsonValue} from '../sdk/json';
import {FetchResponse} from '../plug';
import {SlotContent, VersionedSlotId} from '../slot';

export {FetchResponse} from '../plug';

type FetchingOptions<T extends JsonValue> = {
baseEndpointUrl?: string,
fallback?: T,
Expand Down
17 changes: 0 additions & 17 deletions src/eap.ts

This file was deleted.

88 changes: 16 additions & 72 deletions src/plug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import {Plugin, PluginArguments, PluginFactory} from './plugin';
import {CDN_URL} from './constants';
import {factory as playgroundPluginFactory} from './playground';
import {factory as previewPluginFactory} from './preview';
import {EapFeatures} from './eap';
import {VersionedSlotId, SlotContent} from './slot';
import {JsonValue, JsonObject} from './sdk/json';

Expand All @@ -37,17 +36,7 @@ export type FetchResponse<I extends VersionedSlotId, C extends JsonObject = Json
content: SlotContent<I, C>,
};

/**
* @internal
*/
export type LegacyFetchResponse<I extends VersionedSlotId, C extends JsonObject = JsonObject> = FetchResponse<I, C> & {
/**
* @deprecated Use `content` instead.
*/
payload: SlotContent<I, C>,
};

export interface Plug extends EapFeatures {
export interface Plug {
readonly tracker: TrackerFacade;
readonly user: UserFacade;
readonly session: SessionFacade;
Expand Down Expand Up @@ -76,7 +65,7 @@ export interface Plug extends EapFeatures {
fetch<P extends JsonObject, I extends VersionedSlotId>(
slotId: I,
options?: FetchOptions
): Promise<LegacyFetchResponse<I, P>>;
): Promise<FetchResponse<I, P>>;

unplug(): Promise<void>;
}
Expand Down Expand Up @@ -268,12 +257,6 @@ export class GlobalPlug implements Plug {
);
}

const initializeEap = window.croctEap?.initialize;

if (typeof initializeEap === 'function') {
initializeEap.call(this);
}

Promise.all(pending)
.then(() => {
this.initialize();
Expand Down Expand Up @@ -377,39 +360,21 @@ export class GlobalPlug implements Plug {
.then(result => result === true);
}

public get fetch(): Plug['fetch'] {
return this.eap(
'fetch',
<C extends JsonObject, I extends VersionedSlotId = VersionedSlotId>(
slotId: I,
options: FetchOptions = {},
): Promise<LegacyFetchResponse<I, C>> => {
const [id, version = 'latest'] = slotId.split('@') as [string, `${number}` | 'latest' | undefined];
const logger = this.sdk.getLogger();
public fetch<C extends JsonObject, I extends VersionedSlotId = VersionedSlotId>(
slotId: I,
options: FetchOptions = {},
): Promise<FetchResponse<I, C>> {
const [id, version = 'latest'] = slotId.split('@') as [string, `${number}` | 'latest' | undefined];
const logger = this.sdk.getLogger();

return this.sdk
.contentFetcher
.fetch<SlotContent<I, C>>(id, version === 'latest' ? options : {...options, version: version})
.then(
response => ({
get payload(): SlotContent<I, C> {
logger.warn(
'Accessing the "payload" property of the fetch response is deprecated'
+ ' and will be removed in a future version. Use the "content" property instead.',
);

return response.content;
},
content: response.content,
}),
)
.catch(error => {
logger.error(`Failed to fetch content for slot "${id}@${version}": ${formatCause(error)}`);

throw error;
});
},
);
return this.sdk
.contentFetcher
.fetch<SlotContent<I, C>>(id, version === 'latest' ? options : {...options, version: version})
.catch(error => {
logger.error(`Failed to fetch content for slot "${id}@${version}": ${formatCause(error)}`);

throw error;
});
}

public async unplug(): Promise<void> {
Expand Down Expand Up @@ -459,25 +424,4 @@ export class GlobalPlug implements Plug {
logger.info('🔌 Croct has been unplugged.');
}
}

private eap<T extends keyof EapFeatures>(feature: T, api: EapFeatures[T]): EapFeatures[T] {
const eap = window.croctEap;
const method: EapFeatures[T] | undefined = typeof eap === 'object' ? eap[feature] : undefined;

if (typeof method !== 'function') {
return api;
}

return method.bind(
new Proxy(this, {
get: (plug, property): any => {
if (property === feature) {
return api;
}

return plug[property as keyof GlobalPlug];
},
}),
);
}
}
79 changes: 1 addition & 78 deletions test/plug.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {FetchOptions} from '@croct/sdk/facade/contentFetcherFacade';
import {JsonObject} from '@croct/json';
import {Logger} from '../src/sdk';
import {Plugin, PluginFactory} from '../src/plugin';
import {GlobalPlug, Plug} from '../src/plug';
import {GlobalPlug} from '../src/plug';
import {CDN_URL} from '../src/constants';
import {Token} from '../src/sdk/token';

Expand All @@ -27,8 +27,6 @@ describe('The Croct plug', () => {
delete process.env.NODE_ENV;

croct = new GlobalPlug();

delete window.croctEap;
});

afterEach(async () => {
Expand Down Expand Up @@ -218,18 +216,6 @@ describe('The Croct plug', () => {
expect(initialize).toHaveBeenCalledWith(expect.objectContaining({test: false}));
});

it('should call the EAP initialization hook', () => {
window.croctEap = {
initialize: jest.fn().mockImplementation(function initialize(this: Plug) {
expect(this).toBe(croct);
}),
};

croct.plug({appId: APP_ID});

expect(window.croctEap.initialize).toHaveBeenCalled();
});

it('should log failures initializing plugins', () => {
croct.extend('foo', () => {
throw new Error('Failure');
Expand Down Expand Up @@ -891,7 +877,6 @@ describe('The Croct plug', () => {

await expect(croct.fetch(slotId, options)).resolves.toEqual({
content: content,
payload: content,
});

expect(fetch).toHaveBeenLastCalledWith('foo', options);
Expand Down Expand Up @@ -954,7 +939,6 @@ describe('The Croct plug', () => {

await expect(croct.fetch(slotId, options)).resolves.toEqual({
content: content,
payload: content,
});

expect(fetch).toHaveBeenLastCalledWith('foo', {
Expand Down Expand Up @@ -986,72 +970,11 @@ describe('The Croct plug', () => {

await expect(croct.fetch(slotId, options)).resolves.toEqual({
content: content,
payload: content,
});

expect(fetch).toHaveBeenLastCalledWith('foo', options);
});

it('should delegate the fetch to the EAP hook', async () => {
const logger: Logger = {
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
};

const config: SdkFacadeConfiguration = {
appId: APP_ID,
logger: logger,
};

const sdkFacade = SdkFacade.init(config);

const initialize = jest.spyOn(SdkFacade, 'init').mockReturnValue(sdkFacade);

croct.plug(config);

expect(initialize).toHaveBeenCalledWith(expect.objectContaining(config));

const content: JsonObject = {
title: 'Hello World',
};

const fetch = jest.spyOn(sdkFacade.contentFetcher, 'fetch').mockResolvedValue({
content: content,
});

const eapFetch: Plug['fetch'] = jest.fn().mockImplementation(function hook(this: Plug, ...args: any[]) {
if (!this.initialized) {
// Access the initialized property to ensure the proxy is working.
throw new Error('Croct is not plugged in.');
}

// eslint-disable-next-line prefer-spread -- Necessary to test the hook.
return this.fetch.apply(this, args);
});

window.croctEap = {
fetch: eapFetch,
};

const slotId = 'foo';
const options: FetchOptions = {timeout: 5};

await expect(croct.fetch(slotId, options)).resolves.toEqual({
content: content,
payload: content,
});

expect(eapFetch).toHaveBeenLastCalledWith('foo', options);
expect(fetch).toHaveBeenLastCalledWith('foo', options);

expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining(
'Accessing the "payload" property of the fetch response is deprecated and '
+ 'will be removed in a future version. Use the "content" property instead.',
));
});

it('should fail to fetch a slot content if unplugged', () => {
expect(() => croct.fetch('foo')).toThrow('Croct is not plugged in.');
});
Expand Down