KOMBU Flutter Schema (Mobile-focused)
GraphQL schema package for KOMBU IoT System mobile app. This package provides only the APIs and models relevant to mobile app functionality.
📦 Installation
Add to your pubspec.yaml:
dependencies:
kombu_flutter_schema:
path: ../packages/flutter-schema # Local development
# or
# git:
# url: https://github.com/your-org/kombu
# path: packages/flutter-schema
Then run:
flutter pub get
🚀 Usage
Import
import 'package:kombu_flutter_schema/kombu_flutter_schema.dart';
import 'package:amplify_flutter/amplify_flutter.dart';
Query User
// Get current user
final response = await Amplify.API.query(
request: GraphQLRequest(
document: UserQueries.getUser,
variables: {'id': userId},
),
).response;
if (response.hasErrors) {
print('Error: ${response.errors}');
} else {
final userData = response.data?['getUser'];
final user = User.fromJson(userData as Map<String, dynamic>);
print('User: ${user.fullName}');
}
Update User Profile
final response = await Amplify.API.mutate(
request: GraphQLRequest(
document: UserMutations.updateUser,
variables: {
'input': {
'id': userId,
'fullName': 'New Name',
'phoneNumber': '+84123456789',
},
},
),
).response;
Deactivate User (Custom Mutation)
final response = await Amplify.API.mutate(
request: GraphQLRequest(
document: UserMutations.deactivateUser,
variables: {
'userId': userId, // or email if useEmail is true
'useEmail': false,
},
),
).response;
if (!response.hasErrors) {
final result = response.data?['deactivateUser'];
if (result['success']) {
print('User deactivated successfully');
} else {
print('Error: ${result['error']}');
}
}
Reactivate User (Custom Mutation)
final response = await Amplify.API.mutate(
request: GraphQLRequest(
document: UserMutations.reactivateUser,
variables: {
'userId': userId, // or email if useEmail is true
'useEmail': false,
},
),
).response;
if (!response.hasErrors) {
final result = response.data?['reactivateUser'];
if (result['success']) {
print('User reactivated successfully');
} else {
print('Error: ${result['error']}');
}
}
Remove User (Custom Mutation)
⚠️ Warning: This action is IRREVERSIBLE and will permanently delete the user.
final response = await Amplify.API.mutate(
request: GraphQLRequest(
document: UserMutations.removeUser,
variables: {
'userId': userId, // or email if useEmail is true
'useEmail': false,
},
),
).response;
if (!response.hasErrors) {
final result = response.data?['removeUser'];
if (result['success']) {
print('User removed successfully');
} else {
print('Error: ${result['error']}');
}
}
List Devices
final response = await Amplify.API.query(
request: GraphQLRequest(
document: DeviceQueries.listDevices,
variables: {
'filter': {
'userId': {'eq': userId},
},
'limit': 20,
},
),
).response;
if (!response.hasErrors) {
final items = response.data?['listDevices']?['items'] as List?;
final devices = items?.map((item) => Device.fromJson(item as Map<String, dynamic>)).toList();
print('Devices: ${devices?.length}');
}
Create Device
final response = await Amplify.API.mutate(
request: GraphQLRequest(
document: DeviceMutations.createDevice,
variables: {
'input': {
'deviceId': 'ESP32-ABC123',
'userId': currentUserId,
'deviceName': 'Living Room Heater',
'deviceType': 'kombu_brewer',
'location': 'Living Room',
'status': 'offline',
},
},
),
).response;
if (!response.hasErrors) {
final deviceData = response.data?['createDevice'];
final device = Device.fromJson(deviceData as Map<String, dynamic>);
print('Device created: ${device.deviceName}');
}
Update Device
final response = await Amplify.API.mutate(
request: GraphQLRequest(
document: DeviceMutations.updateDevice,
variables: {
'input': {
'id': deviceId,
'deviceName': 'New Device Name',
'location': 'Kitchen',
},
},
),
).response;
Push Command to IoT Device
Option 1: Using Helper Method (Recommended)
import 'package:kombu_flutter_schema/kombu_flutter_schema.dart';
// Push command using helper method (automatically handles payload stringification)
final result = await PushCommandHelper.pushCommand(
topic: 'kombu/device-id/down/command',
payload: {
'command': 'setTemperature',
'temperature': 75,
'heater': 'f1',
},
);
if (result.success) {
print('Command sent successfully! Message ID: ${result.messageId}');
} else {
print('Failed to send command: ${result.error}');
}
Option 2: Using Raw GraphQL Mutation
import 'package:kombu_flutter_schema/kombu_flutter_schema.dart';
import 'package:amplify_flutter/amplify_flutter.dart';
import 'dart:convert';
// Push command using raw GraphQL mutation
final payload = jsonEncode({
'command': 'setTemperature',
'temperature': 75,
'heater': 'f1',
});
final response = await Amplify.API.mutate(
request: GraphQLRequest<String>(
document: DeviceMutations.pushCommand,
variables: {
'topic': 'kombu/device-id/down/command',
'payload': payload,
},
),
).response;
if (!response.hasErrors) {
final data = jsonDecode(response.data!);
final result = PushCommandResponse.fromJson(data['pushCommand']);
print('Success: ${result.success}, Message ID: ${result.messageId}');
} else {
print('Error: ${response.errors}');
}
Register Device Token (Push Notification)
Option 1: Direct GraphQL Mutations
Use the mutations directly (recommended for full control):
import 'package:kombu_flutter_schema/kombu_flutter_schema.dart';
import 'package:amplify_flutter/amplify_flutter.dart';
// Create device token
final response = await Amplify.API.mutate(
request: GraphQLRequest(
document: DeviceTokenMutations.createDeviceToken,
variables: {
'input': {
'tokenId': 'token_123',
'userId': 'user-id',
'deviceToken': 'fcm-token',
'platform': 'android',
'deviceId': 'device-id',
'isActive': true,
},
},
),
).response;
// Update device token
final updateResponse = await Amplify.API.mutate(
request: GraphQLRequest(
document: DeviceTokenMutations.updateDeviceToken,
variables: {
'input': {
'id': 'token-record-id',
'deviceToken': 'new-fcm-token',
'platform': 'android',
'isActive': true,
},
},
),
).response;
Option 2: Auto Register (Using Helper)
Automatically checks for existing token and updates or creates accordingly:
import 'package:kombu_flutter_schema/kombu_flutter_schema.dart';
final helper = PushNotificationHelper();
await helper.registerDeviceToken(userId);
This method:
- Queries existing tokens using
DeviceTokenQueries.tokensByUser - Updates token if exists using
DeviceTokenMutations.updateDeviceToken - Creates new token if not exists using
DeviceTokenMutations.createDeviceToken
Option 3: Manual Create/Update
If you want more control, you can use the public methods directly:
// Create new device token
final success = await helper.createDeviceToken(
userId: 'user-id',
deviceToken: 'fcm-token-value',
platform: 'android', // or 'ios'
deviceId: 'device-id', // optional
appVersion: '1.0.0', // optional
);
// Update existing device token
final updated = await helper.updateDeviceToken(
tokenRecordId: 'token-record-id',
deviceToken: 'new-fcm-token-value',
platform: 'android',
appVersion: '1.0.1', // optional
);
Get Notifications
final response = await Amplify.API.query(
request: GraphQLRequest(
document: NotificationQueries.notificationsByUser,
variables: {
'userId': userId,
'limit': 20,
},
),
).response;
if (!response.hasErrors) {
final items = response.data?['notificationsByUser']?['items'] as List?;
final notifications = items?.map((item) => Notification.fromJson(item as Map<String, dynamic>)).toList();
}
Mark Notification as Read
final response = await Amplify.API.mutate(
request: GraphQLRequest(
document: NotificationMutations.updateNotification,
variables: {
'input': {
'id': notificationId,
'status': 'read',
'readAt': DateTime.now().toIso8601String(),
},
},
),
).response;
📚 Available APIs
Models
- User: User profile information
- Device: IoT device information
- DeviceToken: Push notification device tokens
- Notification: User notifications
Queries
User
UserQueries.getUser- Get user by ID
Device
DeviceQueries.getDevice- Get device by IDDeviceQueries.listDevices- List devices for user
DeviceToken
DeviceTokenQueries.getDeviceToken- Get device token by IDDeviceTokenQueries.listDeviceTokens- List device tokensDeviceTokenQueries.tokensByUser- Query tokens by user
Notification
NotificationQueries.getNotification- Get notification by IDNotificationQueries.listNotifications- List notificationsNotificationQueries.notificationsByUser- Query notifications by user (sorted by sentAt)
Mutations
User
UserMutations.updateUser- Update user profileUserMutations.deactivateUser- Deactivate user (custom mutation)UserMutations.reactivateUser- Reactivate user (custom mutation)UserMutations.removeUser- Remove user permanently (custom mutation)
Device
DeviceMutations.createDevice- Create new deviceDeviceMutations.updateDevice- Update device (name, location, etc.)DeviceMutations.pushCommand- Push command to AWS IoT Core topic (GraphQL mutation)
DeviceToken
DeviceTokenMutations.createDeviceToken- Register device tokenDeviceTokenMutations.updateDeviceToken- Update device tokenDeviceTokenMutations.deleteDeviceToken- Unregister device token
Notification
NotificationMutations.updateNotification- Update notification (mark as read)
Helpers
Push Command Helper
PushCommandHelper.pushCommand()- Push command using helper method (recommended)PushCommandHelper.pushCommandRaw()- Push command using raw GraphQL mutation (advanced)
🔒 Authentication
All GraphQL operations require authentication via AWS Cognito. Make sure to:
- Initialize Amplify with Cognito configuration
- Sign in user before making API calls
- Include authentication headers in requests (handled automatically by Amplify)
📝 Notes
What's NOT Included
This mobile-focused schema does NOT include:
- DeviceTelemetry: Use MQTT subscriptions for real-time telemetry
- DeviceConfiguration: Backend/internal only
- Timer: May be added in future versions
- Alert: May be added in future versions
- Firmware: Admin-only operations
User Creation
User creation is handled by AWS Cognito sign-up, not GraphQL. Use Amplify.Auth.signUp() instead.
Real-time Data
For real-time device telemetry and status updates, use MQTT subscriptions via Amplify PubSub, not GraphQL queries.
🛠️ Development
Build
cd packages/flutter-schema
flutter pub get
flutter analyze
Format
dart format lib/
📄 License
See LICENSE file for details.
Libraries
- kombu_flutter_schema
- KOMBU IoT System - GraphQL Schema for Flutter/Dart (Mobile-focused)