入门
安装依赖到pubspec.yaml
dependencies:
parse_server_sdk: ^1.0.22复制代码
如果是第一次调用,把一下代码加入
await Parse().initialize(
keyApplicationId,
keyParseServerUrl);复制代码
如果您想使用安全存储或使用Flutter web / desktop SDK,请更改为以下CoreStorage实例,
await Parse().initialize(
keyParseApplicationId,
keyParseServerUrl,
coreStore: await CoreStoreSembastImp.getInstance());复制代码
在使用Parse Server实例时也可以添加其他的一些参数
await Parse().initialize(
keyApplicationId,
keyParseServerUrl,
masterKey: keyParseMasterKey, // Required for Back4App and others
clientKey: keyParseClientKey, // Required for some setups
debug: true, // 启用时,会将日志打印到控制台
liveQueryUrl: keyLiveQueryUrl, // Required if using LiveQuery
autoSendSessionId: true, // Some confurations require this to be true
securityContext: securityContext, // Again, required for some setups
coreStore: await CoreStoreSharedPrefsImp.getInstance()); // Will use SharedPreferences instead of Sembast as an internal DB复制代码
Object(对象)
你可以通过调用以下代码来保存一个customer对象
var dietPlan = ParseObject('DietPlan')
..set('Name', 'Ketogenic')
..set('Fat', 65);
await dietPlan.save();复制代码
验证对象是否已成功保存的方法是
var response = await dietPlan.save();
if (response.success) {
dietPlan = response.results.first;
}复制代码
支持的类型:
- String
- Double
- Int
- Boolean
- Datetime
- File(文件)
- Geopoint
- ParseObject/ParseUser (Pointer)
- Map
- List (所有类型都支持)
然后,您可以使用下面的方法进行操作:
- Get
- GetAll
- Create
- Save
- Query - By object Id
- Delete
- Complex queries as shown above
- Pin
- Plenty more
- Counters
- Array Operators
自定义对象
通过执行以下操作,可以创建自己的ParseObjects或将现有Objects转换为ParseObjects
class DietPlan extends ParseObject implements ParseCloneable {
DietPlan() : super(_keyTableName);
DietPlan.clone(): this();
/// Looks strangely hacky but due to Flutter not using reflection, we have to
/// mimic a clone
@override clone(Map map) => DietPlan.clone()..fromJson(map);
static const String _keyTableName = 'Diet_Plans';
static const String keyName = 'Name';
String get name => get<String>(keyName);
set name(String name) => set<String>(keyName, name);
}复制代码
往对象里面添加新值
下面这个例子先调用set去添加变量RandomInt,并且赋值为8
dietPlan.set<int>('RandomInt', 8);
var randomInt = dietPlan.get<int>('RandomInt');复制代码
用pins来保存对象
在对象上调用pin()来保存对象
dietPlan.pin();复制代码
然后用fromPin去查找这个对象
var dietPlan = DietPlan().fromPin('OBJECT ID OF OBJECT');复制代码
增加对象中的计数器值
声明式
var response = await dietPlan.increment("count", 1);复制代码
或者用函数操作
dietPlan.setIncrement('count', 1);
dietPlan.setDecrement('count', 1);
var response = dietPlan.save()复制代码
在对象中对数组进行操作
声明式
var response = await dietPlan.add("listKeywords", ["a", "a","d"]);
var response = await dietPlan.addUnique("listKeywords", ["a", "a","d"]);
var response = await dietPlan.remove("listKeywords", ["a"]);复制代码
或者用函数操作
dietPlan.setAdd('listKeywords', ['a','a','d']);
dietPlan.setAddUnique('listKeywords', ['a','a','d']);
dietPlan.setRemove('listKeywords', ['a']);
var response = dietPlan.save()复制代码
查询
一旦设置了项目并初始化了实例,就可以通过调用
var apiResponse = await ParseObject('ParseTableName').getAll();
if (apiResponse.success){
for (var testObject in apiResponse.result) {
print(ApplicationConstants.APP_NAME + ": " + testObject.toString());
}
}复制代码
或者也可以通过objectId去得到一个对象
var dietPlan = await DietPlan().getObject('R5EonpUDWy');
if (dietPlan.success) {
print(ApplicationConstants.keyAppName + ": " + (dietPlan.result as DietPlan).toString());
} else {
print(ApplicationConstants.keyAppName + ": " + dietPlan.exception.message);
}复制代码
复杂查询
您可以通过创建复杂的查询来测试数据库
var queryBuilder = QueryBuilder<DietPlan>(DietPlan())
..startsWith(DietPlan.keyName, "Keto")
..greaterThan(DietPlan.keyFat, 64)
..lessThan(DietPlan.keyFat, 66)
..equals(DietPlan.keyCarbs, 5);
var response = await queryBuilder.query();
if (response.success) {
print(ApplicationConstants.keyAppName + ": " + ((response.results as List<dynamic>).first as DietPlan).toString());
} else {
print(ApplicationConstants.keyAppName + ": " + response.exception.message);
}复制代码
有以下功能可用
- Equal(相等)
- Contains(包含)
- LessThan(小于)
- LessThanOrEqualTo(小于或等于)
- GreaterThan(大于)
- GreaterThanOrEqualTo(大于或等于)
- NotEqualTo(不等于)
- StartsWith()
- EndsWith
- Exists(存在)
- Near(相邻)
- WithinMiles
- WithinKilometers
- WithinRadians
- WithinGeoBox
- Regex
- Order
- Limit
- Skip
- Ascending
- Descending
- Plenty more!
关系查询
如果要检索字段包含与另一个查询匹配的对象的对象,可以使用whereMatchesQuery
。例如,假设您有一个post类和一个comment类,其中每个comment都有一个指向其父类post的指针。您可以通过执行以下操作在带有images的posts找到comments:
QueryBuilder<ParseObject> queryPost =
QueryBuilder<ParseObject>(ParseObject('Post'))
..whereValueExists('image', true);
QueryBuilder<ParseObject> queryComment =
QueryBuilder<ParseObject>(ParseObject('Comment'))
..whereMatchesQuery('post', queryPost);
var apiResponse = await queryComment.query();复制代码
如果要检索字段中包含与另一个查询不匹配的对象的对象,可以使用whereDoesNotMatchQuery
条件。假设您有一个post类和一个comment类,其中每个comment都有一个指向其父post的指针。通过执行以下操作,
QueryBuilder<ParseObject> queryPost =
QueryBuilder<ParseObject>(ParseObject('Post'))
..whereValueExists('image', true);
QueryBuilder<ParseObject> queryComment =
QueryBuilder<ParseObject>(ParseObject('Comment'))
..whereDoesNotMatchQuery('post', queryPost);
var apiResponse = await queryComment.query();复制代码
计算对象个数
如果您只关心特定玩家玩的游戏数量:
QueryBuilder<ParseObject> queryPlayers =
QueryBuilder<ParseObject>(ParseObject('GameScore'))
..whereEqualTo('playerName', 'Jonathan Walsh');
var apiResponse = await queryPlayers.count();
if (apiResponse.success && apiResponse.result != null) {
int countGames = apiResponse.count;
}复制代码
实时查询
此工具允许您订阅感兴趣的QueryBuilder。一旦订阅,服务器将在实时创建或更新与QueryBuilder匹配的ParseObject时通知客户机。
Parse LiveQuery包含两部分:LiveQuery服务器和LiveQuery客户端。为了使用实时查询,您需要同时设置这两个查询。
在此处找到服务器上的分析服务器配置指南 docs.parseplatform.org/parse-serve… 这不是本文的一部分。
通过在parse()中输入参数livequeryurl初始化parse live查询。初始化:
Parse().initialize(
keyApplicationId,
keyParseServerUrl,
clientKey: keyParseClientKey,
debug: true,
liveQueryUrl: keyLiveQueryUrl,
autoSendSessionId: true);复制代码
声明 LiveQuery:
final LiveQuery liveQuery = LiveQuery();复制代码
设置将由LiveQuery监视的QueryBuilder:
QueryBuilder<ParseObject> query =
QueryBuilder<ParseObject>(ParseObject('TestAPI'))
..whereEqualTo('intNumber', 1);复制代码
创建订阅
await liveQuery.subscribe(query);复制代码
事件处理
创建事件
liveQuery.on(LiveQueryEvent.create, (value) {
print('*** CREATE ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).updatedAt);
print((value as ParseObject).createdAt);
print((value as ParseObject).get('objectId'));
print((value as ParseObject).get('updatedAt'));
print((value as ParseObject).get('createdAt'));
});复制代码
更新事件
liveQuery.on(LiveQueryEvent.update, (value) {
print('*** UPDATE ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).updatedAt);
print((value as ParseObject).createdAt);
print((value as ParseObject).get('objectId'));
print((value as ParseObject).get('updatedAt'));
print((value as ParseObject).get('createdAt'));
});复制代码
进入事件
liveQuery.on(LiveQueryEvent.enter, (value) {
print('*** ENTER ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).updatedAt);
print((value as ParseObject).createdAt);
print((value as ParseObject).get('objectId'));
print((value as ParseObject).get('updatedAt'));
print((value as ParseObject).get('createdAt'));
});复制代码
离开事件
liveQuery.on(LiveQueryEvent.leave, (value) {
print('*** LEAVE ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).updatedAt);
print((value as ParseObject).createdAt);
print((value as ParseObject).get('objectId'));
print((value as ParseObject).get('updatedAt'));
print((value as ParseObject).get('createdAt'));
});复制代码
销毁事件
liveQuery.on(LiveQueryEvent.delete, (value) {
print('*** DELETE ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).updatedAt);
print((value as ParseObject).createdAt);
print((value as ParseObject).get('objectId'));
print((value as ParseObject).get('updatedAt'));
print((value as ParseObject).get('createdAt'));
});复制代码
退订
await liveQuery.unSubscribe();复制代码
用户(User)
您可以使用此SDK正常创建和控制用户
注册用户前要先创建用户
var user = ParseUser().create("TestFlutter", "TestPassword123", "TestFlutterSDK@gmail.com");复制代码
然后注册用户
var response = await user.signUp();
if (response.success) user = response.result;复制代码
用户登录
var response = await user.login();
if (response.success) user = response.result;复制代码
用户登出
var response = await user.logout();
if (response.success) {
print('User logout');
}复制代码
同样,你可以在用户登录后管理sessions和tokens。
user = ParseUser.currentUser();复制代码
其他的一些用户操作方法
- Request Password Reset
- Verification Email Request
- Get all users
- Save
- Destroy user
- Queries
ParseACL-对象的安全性
对于任何对象,您可以指定允许哪些用户读取对象,以及允许哪些用户修改对象。为了支持这种安全性,每个对象都有一个访问控制列表,由ParseAcl类实现。
如果未指定parseAcl(parseUser类除外),则所有对象都设置为public进行读写。使用parsacl的最简单方法是指定一个对象只能由单个用户读或写。要创建这样的对象,首先必须有一个登录的parseuser。然后,新的parseacl(用户)生成一个parseacl,限制对该用户的访问。与任何其他属性一样,保存对象时更新对象的ACL。
ParseUser user = await ParseUser.currentUser() as ParseUser;
ParseACL parseACL = ParseACL(owner: user);
ParseObject parseObject = ParseObject("TestAPI");
...
parseObject.setACL(parseACL);
var apiResponse = await parseObject.save();复制代码
还可以根据每个用户授予权限。可以使用setreadaccess和setwriteaccess分别向parseacl添加权限。
ParseUser user = await ParseUser.currentUser() as ParseUser;
ParseACL parseACL = ParseACL();
//grant total access to current user
parseACL.setReadAccess(userId: user.objectId, allowed: true);
parseACL.setWriteAccess(userId: user.objectId, allowed: true);
//grant read access to userId: 'TjRuDjuSAO'
parseACL.setReadAccess(userId: 'TjRuDjuSAO', allowed: true);
parseACL.setWriteAccess(userId: 'TjRuDjuSAO', allowed: false);
ParseObject parseObject = ParseObject("TestAPI");
...
parseObject.setACL(parseACL);
var apiResponse = await parseObject.save();复制代码
还可以使用setpublicreadaccess和setpublicwriteaccess一次授予所有用户权限。
ParseACL parseACL = ParseACL();
parseACL.setPublicReadAccess(allowed: true);
parseACL.setPublicWriteAccess(allowed: true);
ParseObject parseObject = ParseObject("TestAPI");
...
parseObject.setACL(parseACL);
var apiResponse = await parseObject.save();复制代码
禁止的操作(例如删除您没有写入权限的对象)将导致代码为101的ParseError:“ObjectNotFound”。出于安全目的,这会阻止客户机区分哪些对象ID存在但受到保护,以及哪些对象ID根本不存在。
可以使用以下方法检索对象的ACL列表:
ParseACL parseACL = parseObject.getACL();复制代码
配置(Config)
SDK支持Parse Config。可以通过调用以下命令从服务器获取所有配置的映射:
var response = await ParseConfig().getConfigs();复制代码
还有添加配置
ParseConfig().addConfig('TestConfig', 'testing');复制代码
云函数(Cloud Functions)
这个SDK支持所有云函数
执行返回ParseObject类型的云函数
final ParseCloudFunction function = ParseCloudFunction('hello');
final ParseResponse result =
await function.executeObjectFunction<ParseObject>();
if (result.success) {
if (result.result is ParseObject) {
final ParseObject parseObject = result.result;
print(parseObject.className);
}
}复制代码
使用参数执行云函数
final ParseCloudFunction function = ParseCloudFunction('hello');
final Map<String, String> params = <String, String>{'plan': 'paid'};
function.execute(parameters: params);复制代码
此库的其他功能
Main:
- Installation (View the example application)
- GeoPoints (View the example application)
- Files (View the example application)
- Persistent storage
- Debug Mode - Logging API calls
- Manage Session ID's tokens
User:
- Queries
- Anonymous (View the example application)
- 3rd Party Authentication
Objects:
- Create new object
- Extend Parse Object and create local objects that can be saved and retreived
- Queries
作者(Author)
原作者信息-----This project was authored by Phill Wiggins. You can contact me at phill.wiggins@gmail.com
翻译来自Mizuki Dragon-----1933908466@qq.com,这个库我会慢慢翻译下去的,边用边翻译。