0
# Native Module Access
1
2
Proxy system providing dynamic access to native modules with automatic method binding, error handling, and cross-platform compatibility.
3
4
## Capabilities
5
6
### NativeModulesProxy Object
7
8
Central proxy object that provides access to all available native modules with automatic method binding and argument validation.
9
10
```typescript { .api }
11
/**
12
* Proxy object providing access to native modules
13
* Each property corresponds to a registered native module
14
*/
15
const NativeModulesProxy: { [moduleName: string]: ProxyNativeModule };
16
17
/**
18
* Shape of each native module proxy
19
*/
20
interface ProxyNativeModule {
21
[propertyName: string]: any;
22
addListener: (eventName: string) => void;
23
removeListeners: (count: number) => void;
24
}
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
import { NativeModulesProxy } from "@unimodules/core";
31
32
// Access a native module
33
const CameraModule = NativeModulesProxy.ExpoCamera;
34
35
if (CameraModule) {
36
// Call native methods (returns Promise)
37
try {
38
const result = await CameraModule.takePictureAsync({
39
quality: 0.8,
40
base64: false
41
});
42
console.log('Picture saved to:', result.uri);
43
} catch (error) {
44
console.error('Failed to take picture:', error);
45
}
46
}
47
48
// Check if module is available
49
const LocationModule = NativeModulesProxy.ExpoLocation;
50
if (!LocationModule) {
51
console.warn('Location module not available on this platform');
52
}
53
```
54
55
### Module Method Invocation
56
57
All native module methods are automatically bound and return Promises with built-in error handling.
58
59
**Usage Examples:**
60
61
```typescript
62
import { NativeModulesProxy } from "@unimodules/core";
63
64
// Native methods with different signatures
65
const FileSystemModule = NativeModulesProxy.ExpoFileSystem;
66
67
if (FileSystemModule) {
68
// Method with no arguments
69
const documentDirectory = await FileSystemModule.getDocumentDirectoryAsync();
70
71
// Method with single argument
72
const fileInfo = await FileSystemModule.getInfoAsync('/path/to/file.txt');
73
74
// Method with multiple arguments
75
await FileSystemModule.writeAsStringAsync(
76
'/path/to/file.txt',
77
'Hello world',
78
{ encoding: 'utf8' }
79
);
80
81
// Method with options object
82
const downloadResult = await FileSystemModule.downloadAsync(
83
'https://example.com/file.pdf',
84
'/local/path/file.pdf',
85
{
86
headers: { 'Authorization': 'Bearer token' },
87
progressCallback: (progress) => {
88
console.log(`Downloaded ${progress.totalBytesWritten} bytes`);
89
}
90
}
91
);
92
}
93
```
94
95
### Error Handling
96
97
Native module methods automatically validate arguments and provide detailed error messages.
98
99
**Usage Examples:**
100
101
```typescript
102
import { NativeModulesProxy, CodedError } from "@unimodules/core";
103
104
const SomeModule = NativeModulesProxy.SomeModule;
105
106
try {
107
// This will throw an error if wrong number of arguments
108
await SomeModule.methodExpectingTwoArgs('arg1'); // Missing second argument
109
} catch (error) {
110
console.error(error.message);
111
// "Native method SomeModule.methodExpectingTwoArgs expects 2 arguments but received 1"
112
}
113
114
try {
115
// Module-specific errors
116
await SomeModule.someMethodThatMightFail();
117
} catch (error) {
118
if (error instanceof CodedError) {
119
console.error(`Module error ${error.code}: ${error.message}`);
120
}
121
}
122
```
123
124
### Module Constants Access
125
126
Access compile-time constants exported by native modules.
127
128
**Usage Examples:**
129
130
```typescript
131
import { NativeModulesProxy } from "@unimodules/core";
132
133
const ConstantsModule = NativeModulesProxy.ExpoConstants;
134
135
if (ConstantsModule) {
136
// Access module constants
137
console.log('App version:', ConstantsModule.appVersion);
138
console.log('Device model:', ConstantsModule.deviceModel);
139
console.log('System version:', ConstantsModule.systemVersion);
140
141
// Platform-specific constants
142
if (Platform.OS === 'ios') {
143
console.log('iOS bundle ID:', ConstantsModule.iosBundleIdentifier);
144
} else if (Platform.OS === 'android') {
145
console.log('Android package name:', ConstantsModule.androidPackageName);
146
}
147
}
148
```
149
150
### Event Listener Management
151
152
Native modules support event listeners through standardized methods.
153
154
**Usage Examples:**
155
156
```typescript
157
import { NativeModulesProxy } from "@unimodules/core";
158
159
const SensorModule = NativeModulesProxy.AccelerometerModule;
160
161
if (SensorModule) {
162
// Add event listener (handled by EventEmitter internally)
163
SensorModule.addListener('accelerometerData');
164
165
// Remove listeners (handled by EventEmitter internally)
166
SensorModule.removeListeners(1);
167
}
168
```
169
170
## Advanced Usage
171
172
### Dynamic Module Discovery
173
174
```typescript
175
import { NativeModulesProxy } from "@unimodules/core";
176
177
// Get all available module names
178
const availableModules = Object.keys(NativeModulesProxy);
179
console.log('Available native modules:', availableModules);
180
181
// Check for specific module
182
function hasModule(moduleName: string): boolean {
183
return moduleName in NativeModulesProxy && NativeModulesProxy[moduleName] != null;
184
}
185
186
if (hasModule('ExpoCamera')) {
187
console.log('Camera module is available');
188
}
189
```
190
191
### Conditional Native Calls
192
193
```typescript
194
import { NativeModulesProxy, Platform } from "@unimodules/core";
195
196
// Platform-specific module access
197
const module = NativeModulesProxy.SomePlatformSpecificModule;
198
199
if (module && Platform.OS === 'ios') {
200
await module.iosSpecificMethod();
201
} else if (module && Platform.OS === 'android') {
202
await module.androidSpecificMethod();
203
} else {
204
console.warn('Platform-specific functionality not available');
205
}
206
```
207
208
### Module Method Introspection
209
210
```typescript
211
import { NativeModulesProxy } from "@unimodules/core";
212
213
const module = NativeModulesProxy.SomeModule;
214
215
if (module) {
216
// Check if specific method exists
217
if (typeof module.someMethod === 'function') {
218
await module.someMethod();
219
} else {
220
console.warn('Method someMethod not available in this version');
221
}
222
}
223
```
224
225
## Types
226
227
```typescript { .api }
228
type NativeModuleMethod = (...args: any[]) => Promise<any>;
229
230
interface ModuleMethodInfo {
231
name: string;
232
key: string;
233
argumentsCount: number;
234
}
235
236
interface NativeModuleDefinition {
237
[exportedMethodsKey]: { [moduleName: string]: ModuleMethodInfo[] };
238
[modulesConstantsKey]: { [moduleName: string]: any };
239
}
240
```