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

v6 - Enhancing the Core.initialize to perform variable checks #2561

Merged
merged 5 commits into from
Feb 21, 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
1 change: 1 addition & 0 deletions packages/lib/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ module.exports = {
jest: true,
es6: true
},
ignorePatterns: [ "*_*.*"],
settings: {
react: {
pragma: 'h',
Expand Down
34 changes: 12 additions & 22 deletions packages/lib/src/core/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,37 +295,27 @@ describe('Core', () => {

describe('Initialising without a countryCode', () => {
test('AdvancedFlow, without a countryCode, should throw an error', () => {
expect(() => {
new AdyenCheckout({
environment: 'test',
environmentUrls: {
api: 'https://localhost:8080/checkoutshopper/'
},
clientKey: 'devl_FX923810'
});
}).toThrow('You must specify a countryCode when initializing checkout');
});
const core = new AdyenCheckout({
environment: 'test',
environmentUrls: {
api: 'https://localhost:8080/checkoutshopper/'
},
clientKey: 'devl_FX923810'
});

const onError = jest.fn(() => {});
expect(async () => await core.initialize()).rejects.toThrow('You must specify a countryCode');
});

test('SessionsFlow, without a countryCode, should throw an error', async () => {
test('SessionsFlow, without a countryCode, should throw an error', () => {
delete sessionSetupResponseMock.countryCode;

const checkout = new AdyenCheckout({
countryCode: 'US',
environment: 'test',
clientKey: 'test_123456',
session: { id: 'session-id', sessionData: 'session-data' },
onError
});

let err;

await checkout.initialize().catch(e => {
err = e;
session: { id: 'session-id', sessionData: 'session-data' }
});

expect(onError).toBeCalledWith(err);
expect(async () => await checkout.initialize()).rejects.toThrow('You must specify a countryCode');
});
});
});
47 changes: 28 additions & 19 deletions packages/lib/src/core/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import { hasOwnProperty } from '../utils/hasOwnProperty';
import { Resources } from './Context/Resources';
import { SRPanel } from './Errors/SRPanel';
import registry, { NewableComponent } from './core.registry';
import { DEFAULT_LOCALE } from '../language/config';
import { cleanupFinalResult, sanitizeResponse, verifyPaymentDidNotFail } from '../components/internal/UIElement/utils';
import AdyenCheckoutError, { IMPLEMENTATION_ERROR } from './Errors/AdyenCheckoutError';
import { ANALYTICS_ACTION_STR } from './Analytics/constants';
import { THREEDS2_FULL } from '../components/ThreeDS2/config';
import { DEFAULT_LOCALE } from '../language/config';

class Core implements ICore {
public session?: Session;
Expand Down Expand Up @@ -59,11 +59,6 @@ class Core implements ICore {
constructor(props: CoreConfiguration) {
this.createFromAction = this.createFromAction.bind(this);

// If it's not a session - check if we have the required countryCode
if (!props.session && !hasOwnProperty(props, 'countryCode')) {
throw new AdyenCheckoutError(IMPLEMENTATION_ERROR, 'You must specify a countryCode when initializing checkout');
}

this.setOptions(props);

this.loadingContext = resolveEnvironment(this.options.environment, this.options.environmentUrls?.api);
Expand All @@ -80,17 +75,20 @@ class Core implements ICore {
window['adyenWebVersion'] = Core.version.version;
}

public initialize(): Promise<this> {
public async initialize(): Promise<this> {
await this.initializeCore();
this.validateCoreConfiguration();
this.createCoreModules();
return this;
}

private async initializeCore(): Promise<this> {
if (this.session) {
return this.session
.setupSession(this.options)
.then(sessionResponse => {
const { amount, shopperLocale, countryCode, paymentMethods, ...rest } = sessionResponse;

if (!hasOwnProperty(sessionResponse, 'countryCode')) {
throw new AdyenCheckoutError(IMPLEMENTATION_ERROR, 'You must specify a countryCode when creating a session');
}

this.setOptions({
...rest,
amount: this.options.order ? this.options.order.remainingAmount : amount,
Expand All @@ -99,7 +97,6 @@ class Core implements ICore {
});

this.createPaymentMethodsList(paymentMethods);
this.createCoreModules();

return this;
})
Expand All @@ -110,11 +107,27 @@ class Core implements ICore {
}

this.createPaymentMethodsList();
this.createCoreModules();

return Promise.resolve(this);
}

private validateCoreConfiguration(): void {
// @ts-ignore This property does not exist, although merchants might be using when migrating from v5 to v6
if (this.options.paymentMethodsConfiguration) {
console.warn('WARNING: "paymentMethodsConfiguration" is supported only by Drop-in.');
}

if (!this.options.locale) {
this.setOptions({ locale: DEFAULT_LOCALE });
}

if (!this.options.countryCode) {
throw new AdyenCheckoutError(
IMPLEMENTATION_ERROR,
'You must specify a countryCode when initializing checkout. (If you are using a session then this session should be initialized with a countryCode.)'
);
}
}

/**
* Method used when handling redirects. It submits details using 'onAdditionalDetails' or the Sessions flow if available.
*
Expand Down Expand Up @@ -235,14 +248,10 @@ class Core implements ICore {
* Create or update the config object passed when AdyenCheckout is initialised (environment, clientKey, etc...)
*/
private setOptions = (options: CoreConfiguration): void => {
if (hasOwnProperty(options, 'paymentMethodsConfiguration')) {
console.warn('WARNING: "paymentMethodsConfiguration" is supported only by Drop-in.');
}

this.options = {
...this.options,
...options,
locale: options?.locale || this.options?.locale || DEFAULT_LOCALE
locale: options?.locale || this.options?.locale
};
};

Expand Down
2 changes: 1 addition & 1 deletion packages/lib/src/language/Language.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class Language {
public translations: Record<string, string>;
public readonly customTranslations;

constructor(locale: string, customTranslations: CustomTranslations = {}, translationFile?: Translation) {
constructor(locale = DEFAULT_LOCALE, customTranslations: CustomTranslations = {}, translationFile?: Translation) {
this.customTranslations = formatCustomTranslations(customTranslations, SUPPORTED_LOCALES);
const localesFromCustomTranslations = Object.keys(this.customTranslations);
this.supportedLocales = [...SUPPORTED_LOCALES, ...localesFromCustomTranslations].filter((v, i, a) => a.indexOf(v) === i); // our locales + validated custom locales
Expand Down
2 changes: 1 addition & 1 deletion packages/lib/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,5 @@
"./src/**/*",
"./src/types/custom.d.ts",
],
"exclude": ["node_modules", "./dist/**", "**/*.scss"],
"exclude": ["node_modules", "./dist/**", "**/*.scss", "**/*_*/**"],
}
Loading