@appedge/react-native-data
v0.1.1
Published
AppEdge React Native Data - Data operations and DataQL integration
Maintainers
Readme
@appedge/react-native-data
Data operations and DataQL integration plugin for AppEdge React Native SDK. Provides seamless data management with automatic authentication routing through AppEdge worker.
Features
- DataQL Integration: Custom connection that routes through AppEdge worker
- Automatic Authentication: Injects session tokens into data requests
- Plugin Architecture: Seamlessly integrates with @appedge/react-native-app
- Session Sync: Automatically updates data client when session changes
- Custom Routing: Routes DataQL requests through AppEdge for additional features
Installation
npm install @appedge/react-native-data @appedge/react-native-app dataqlUsage
1. Register the Data Plugin
import React, { useEffect } from 'react';
import { AppProvider, useApp } from '@appedge/react-native-app';
import { Data } from '@appedge/react-native-data';
function App() {
return (
<AppProvider config={{ appToken: 'your-token', workerUrl: 'your-url' }}>
<DataSetup />
</AppProvider>
);
}
function DataSetup() {
const app = useApp();
useEffect(() => {
const initData = async () => {
const data = new Data();
await app.registerPlugin(data);
};
initData();
}, [app]);
return <YourContent />;
}2. Use Data Operations
import { useApp } from '@appedge/react-native-app';
import { Data } from '@appedge/react-native-data';
function DataComponent() {
const app = useApp();
const data = app.getPlugin<Data>('data');
useEffect(() => {
const loadData = async () => {
const dataQL = data?.getData();
if (dataQL) {
// Use DataQL operations
const users = dataQL.collection('users', UserSchema);
const allUsers = await users.find();
console.log('Users:', allUsers);
}
};
loadData();
}, [data]);
return <YourDataComponents />;
}API Reference
Data
The main plugin class that integrates with the App instance:
class Data implements AppPlugin {
readonly name: 'data';
getConnection(): AppEdgeDataQLConnection | undefined;
getData(): DataQLClient | undefined;
onSessionChanged(session: any): Promise<void>;
}AppEdgeDataQLConnection
Custom DataQL connection that routes requests through AppEdge:
class AppEdgeDataQLConnection {
constructor(workerUrl: string, getAuthHeaders: () => Promise<Record<string, string>>);
request(url: string, options: RequestInit): Promise<Response>;
}How It Works
Request Routing
The DataPlugin creates a custom DataQL connection that:
- Intercepts DataQL requests: All data operations go through the custom connection
- Routes through AppEdge: Requests are sent to your AppEdge worker instead of directly to DataQL
- Injects authentication: Automatically adds session tokens and user context
- Passes to DataQL: AppEdge worker forwards requests to DataQL with authentication
React Native App → AppEdge Worker → DataQL Worker
↑ (with auth headers)Authentication Headers
The connection automatically injects these headers:
{
"Authorization": `Bearer ${session.token}`,
"x-session-id": session.sessionId,
"x-user-id": session.userId,
"x-dataql-original-url": originalDataQLUrl
}Session Synchronization
When the session changes (user signs in/out), the Data plugin:
- Receives notification from the App instance
- Updates the DataQL client with new session
- Ensures all subsequent requests use current authentication
DataQL Schema Example
// Define your schema
const UserSchema = {
name: 'String',
email: 'String',
age: 'Int',
isActive: 'Boolean',
};
// Use with the data plugin
const data = app.getPlugin<Data>('data');
const dataQL = data?.getData();
if (dataQL) {
const users = dataQL.collection('users', UserSchema);
// Create
await users.create({
name: 'John Doe',
email: '[email protected]',
age: 30,
isActive: true,
});
// Read
const allUsers = await users.find();
const activeUsers = await users.find({ isActive: true });
// Update
await users.update('user-id', { age: 31 });
// Delete
await users.delete('user-id');
}Request Flow
- DataQL Operation: Your app calls a DataQL method (e.g.,
users.create()) - Custom Connection: Request is intercepted by
AppEdgeDataQLConnection - Route to AppEdge: Request is sent to
${workerUrl}/dataql${originalPath} - Authentication: AppEdge worker receives request with auth headers
- Forward to DataQL: AppEdge processes and forwards to DataQL worker
- Response: Data flows back through the same path
Benefits
Security
- All data requests are authenticated through your AppEdge worker
- Centralized access control and authorization
- Session validation on every request
Flexibility
- Add custom logic in your AppEdge worker before forwarding to DataQL
- Implement rate limiting, caching, or data transformation
- Log and monitor all data operations
Simplicity
- No need to manually handle authentication in data operations
- Automatic session synchronization
- Standard DataQL API with enhanced security
Error Handling
The Data plugin handles connection errors gracefully:
try {
const users = await data.collection('users', UserSchema).find();
} catch (error) {
if (error.message.includes('Auth request failed')) {
// Handle authentication error
await authPlugin.refreshSession();
}
}Integration with Auth
The Data plugin automatically integrates with the Auth plugin:
- Session changes trigger data client updates
- Authentication failures can trigger session refresh
- User context is automatically included in all requests
Development Notes
The DataQL integration is designed to work with the full DataQL package. When DataQL is not available, the plugin provides placeholder interfaces to maintain type safety.
License
MIT
