Skip to content

Instantly share code, notes, and snippets.

@bang9
Created December 11, 2021 08:08
Show Gist options
  • Save bang9/a6b7f0e6a388df5a359ac800a6f3213d to your computer and use it in GitHub Desktop.
Save bang9/a6b7f0e6a388df5a359ac800a6f3213d to your computer and use it in GitHub Desktop.
React-Native Safe Native Module
import Admob from '@invertase/react-native-google-ads'
const INSTALLED_APP_VERSION = '1.0.0';
function checkSemver(v1, v2): boolean {
// ... v1 <= v2
return true;
}
function isValidVersion(start: string, end?: string) {
if (!end) return checkSemver(start, INSTALLED_APP_VERSION)
return checkSemver(start, INSTALLED_APP_VERSION) && checkSemver(INSTALLED_APP_VERSION, end);
}
abstract class NativeModuleImpl<T> {
constructor(private _module: T, private _validVersion: { install: string; uninstall?: string }) {
if (!isValidVersion(_validVersion.install, _validVersion.uninstall)) {
this.onNotMatched();
}
}
protected get module() {
if (this._module) return this._module;
this.onNotFound();
return null;
}
protected onNotFound(): void {
Alert.alert('Sorry', 'You needs to update');
}
protected onNotMatched(): void {
Alert.alert('Sorry', 'Not supported anymore');
}
}
class AdmobNative extends NativeModuleImpl<typeof Admob> {
getAdSize() {
if (!this.module) return 0;
return this.module.BannerAdSize;
}
}
const m = new AdmobNative(NativeModules['RNAdMob'] as any, { install: '0.9.0' });
m.getAdSize();
@bang9
Copy link
Author

bang9 commented Dec 11, 2021

3rd party 의 경우, 모듈의 Entry file 에서 네이티브 모듈을 호출해서 사용 할 가능성이 있을 수 있다.
매번 그 부분들을 체크하고 직접 네이티브 모듈을 import & wrapping 해야할 수 있다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment