@complycube/react-native
Version:
ComplyCube's React Native Mobile SDK library for Identity Verification, KYC, and AML
142 lines (130 loc) • 3.38 kB
text/typescript
import {
Platform,
NativeModules,
NativeEventEmitter,
DeviceEventEmitter,
DeviceEventEmitterStatic,
} from 'react-native';
import Ajv from 'ajv';
import settingsSchema from './verificationSchema';
import betterAjvErrors from 'better-ajv-errors';
class ComplyCubeRN {
complycube: any;
emiter: NativeEventEmitter | DeviceEventEmitterStatic;
errors: any[] = [];
constructor() {
let ComplyCubeRNSDK =
Platform.OS === 'ios'
? NativeModules['ComplyCubeRNSDK']
: NativeModules['ComplyCubeModule'];
this.emiter =
Platform.OS == 'ios'
? new NativeEventEmitter(ComplyCubeRNSDK)
: DeviceEventEmitter;
this.complycube = ComplyCubeRNSDK;
}
_validateSettingsBySchema(settings: any) {
this.errors = [];
const ajv = new Ajv({
allErrors: true,
allowUnionTypes: true,
});
try {
const valid = ajv.validate(settingsSchema, settings);
if (!valid) {
const output = betterAjvErrors(settingsSchema, settings, ajv.errors, {
format: 'cli',
indent: 2,
});
this.onError(output);
return false;
}
return this;
} catch (e: any) {
return false;
}
}
setSettings(settings: any) {
if (this.complycube == null) return false;
try {
if (this._validateSettingsBySchema(settings)) {
this.complycube.setSettings(settings).then((x: any) => {
console.log('Results:', x);
});
} else {
return false;
}
} catch (e: any) {
console.log('Error during setting settings', e.description);
}
return this;
}
_wrapHandler(handler: any, isCustomEvent = false) {
return async (data: any) => {
let _data = data;
if (Platform.OS === 'android') _data = JSON.parse(data);
handler(_data);
if(!isCustomEvent) this.emiter.removeAllListeners();
};
}
addHandlers(
successHandler = () => {},
errorHandler = () => {},
cancelHandler = () => {},
customEventHandler = () => {}
) {
if (!this.emiter) return;
this.emiter.addListener(
'ComplyCubeCustomEvent',
this._wrapHandler(customEventHandler, true)
);
if (Platform.OS === 'ios') {
this.emiter.addListener(
'ComplyCubeSuccess',
this._wrapHandler(successHandler)
);
} else {
DeviceEventEmitter.addListener(
'ComplyCubeSuccess',
this._wrapHandler(successHandler)
);
}
if (Platform.OS === 'ios') {
this.emiter.addListener(
'ComplyCubeError',
this._wrapHandler(errorHandler)
);
} else {
DeviceEventEmitter.addListener(
'ComplyCubeError',
this._wrapHandler(errorHandler)
);
}
if (Platform.OS === 'ios') {
this.emiter.addListener(
'ComplyCubeCancel',
this._wrapHandler(cancelHandler)
);
} else {
DeviceEventEmitter.addListener(
'ComplyCubeCancel',
this._wrapHandler(cancelHandler)
);
}
return this;
}
mount() {
if (this.complycube == null) return;
this.complycube.mount();
}
onError(error_message: any) {
this.errors = [
{
message: error_message,
},
];
this.emiter.emit('ComplyCubeError', { ...this.errors[0] });
throw this.errors[0];
}
}
export default ComplyCubeRN;