Skip to content

Commit 7503391

Browse files
authored
Merge branch 'master' into release/1.0.5
2 parents 0310298 + ca8e30d commit 7503391

File tree

6 files changed

+354
-512
lines changed

6 files changed

+354
-512
lines changed

.idea/workspace.xml

+160-238
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

example/android/gradlew

100644100755
File mode changed.

lib/src/objects/parse_user.dart

+65-249
Original file line numberDiff line numberDiff line change
@@ -1,276 +1,92 @@
11
part of flutter_parse_sdk;
22

3-
class ParseUser extends ParseBase implements ParseCloneable {
3+
class ParseResponse {
4+
bool success = false;
5+
int statusCode = -1;
6+
dynamic result;
7+
ParseError error;
48

5-
ParseUser.clone(Map map): this(map[keyVarUsername],map[keyVarPassword],map[keyVarEmail]);
6-
7-
@override
8-
clone(Map map) => ParseUser.clone(map)..fromJson(map);
9-
10-
static final String path = "$keyEndPointClasses$keyClassUser";
11-
12-
bool _debug;
13-
ParseHTTPClient _client;
14-
15-
Map get acl => super.get<Map>(keyVarAcl);
16-
set acl(Map acl) => set<Map>(keyVarAcl, acl);
17-
18-
String get username => super.get<String>(keyVarUsername);
19-
set username(String username) => set<String>(keyVarUsername, username);
20-
21-
String get password => super.get<String>(keyVarPassword);
22-
set password(String password) => set<String>(keyVarPassword, password);
23-
24-
String get emailAddress => super.get<String>(keyVarEmail);
25-
set emailAddress(String emailAddress) => set<String>(keyVarEmail, emailAddress);
26-
27-
/// Creates an instance of ParseUser
28-
///
29-
/// Users can set whether debug should be set on this class with a [bool],
30-
/// they can also create thier own custom version of [ParseHttpClient]
9+
/// Handles all the ParseObject responses
3110
///
32-
/// Creates a new user locally
33-
///
34-
/// Requires [String] username, [String] password. [String] email address
35-
/// is required as well to create a full new user object on ParseServer. Only
36-
/// username and password is required to login
37-
ParseUser(String username, String password, String emailAddress, {bool debug, ParseHTTPClient client}) : super() {
38-
client == null ? _client = ParseHTTPClient() : _client = client;
39-
_debug = isDebugEnabled(objectLevelDebug: debug);
40-
41-
this.username = username;
42-
this.password = password;
43-
this.emailAddress = emailAddress;
44-
45-
setClassName(keyClassUser);
46-
}
47-
48-
create(String username, String password, [String emailAddress]) {
49-
return ParseUser(username, password, emailAddress);
50-
}
51-
52-
/// Gets the current user from the server
53-
///
54-
/// Current user is stored locally, but in case of a server update [bool]
55-
/// fromServer can be called and an updated version of the [User] object will be
56-
/// returned
57-
getCurrentUserFromServer() async {
58-
// We can't get the current user and session without a sessionId
59-
if (_client.data.sessionId == null) return null;
60-
61-
try {
62-
Uri tempUri = Uri.parse(_client.data.serverUrl);
63-
64-
Uri uri = Uri(
65-
scheme: tempUri.scheme,
66-
host: tempUri.host,
67-
path: "${tempUri.path}$keyEndPointUserName");
68-
69-
final response = await _client
70-
.get(uri, headers: {keyHeaderSessionToken: _client.data.sessionId});
71-
return _handleResponse(response, ParseApiRQ.currentUser);
72-
} on Exception catch (e) {
73-
return _handleException(e, ParseApiRQ.currentUser);
11+
/// There are 4 probable outcomes from a Parse API call,
12+
/// 1. Fail - [ParseResponse()] will be returned with further details
13+
/// 2. Success but no results. [ParseResponse()] is returned.
14+
/// 3. Success with simple OK.
15+
/// 4. Success with results. Again [ParseResponse()] is returned
16+
static handleResponse(dynamic object, Response apiResponse) {
17+
var parseResponse = ParseResponse();
18+
19+
if (apiResponse != null) {
20+
parseResponse.statusCode = apiResponse.statusCode;
21+
22+
if (apiResponse.statusCode != 200 && apiResponse.statusCode != 201) {
23+
return _handleError(parseResponse, apiResponse);
24+
} else if (apiResponse.body == "{\"results\":[]}"){
25+
return _handleSuccessWithNoResults(parseResponse, 1, "Successful request, but no results found");
26+
} else if (apiResponse.body == "OK"){
27+
return _handleSuccessWithNoResults(parseResponse, 2, "Successful request");
28+
} else {
29+
return _handleSuccess(parseResponse, object, apiResponse.body);
30+
}
31+
} else {
32+
parseResponse.error = ParseError(message: "Error reaching server, or server response was null");
33+
return apiResponse;
7434
}
7535
}
76-
/// Gets the current user from storage
77-
///
78-
/// Current user is stored locally, but in case of a server update [bool]
79-
/// fromServer can be called and an updated version of the [User] object will be
80-
/// returned
81-
static currentUser() {
82-
return _getUserFromLocalStore();
83-
}
84-
85-
/// Registers a user on Parse Server
86-
///
87-
/// After creating a new user via [Parse.create] call this method to register
88-
/// that user on Parse
89-
signUp() async {
90-
try {
91-
if (emailAddress == null) return null;
92-
93-
Map<String, dynamic> bodyData = {};
94-
bodyData[keyVarEmail] = emailAddress;
95-
bodyData[keyVarPassword] = password;
96-
bodyData[keyVarUsername] = username;
9736

98-
Uri tempUri = Uri.parse(_client.data.serverUrl);
99-
100-
Uri url = Uri(
101-
scheme: tempUri.scheme,
102-
host: tempUri.host,
103-
path: "${tempUri.path}$path");
104-
105-
final response = await _client.post(url,
106-
headers: {
107-
keyHeaderRevocableSession: "1",
108-
},
109-
body: json.encode(bodyData));
110-
111-
_handleResponse(response, ParseApiRQ.signUp);
112-
return this;
113-
} on Exception catch (e) {
114-
return _handleException(e, ParseApiRQ.signUp);
115-
}
37+
/// Handles exception instead of throwing an exception
38+
static ParseResponse handleException(Exception exception) {
39+
var response = ParseResponse();
40+
response.error = ParseError(message: exception.toString(), isTypeOfException: true);
41+
return response;
11642
}
11743

118-
/// Logs a user in via Parse
119-
///
120-
/// Once a user is created using [Parse.create] and a username and password is
121-
/// provided, call this method to login.
122-
login() async {
123-
try {
124-
Uri tempUri = Uri.parse(_client.data.serverUrl);
125-
126-
Uri url = Uri(
127-
scheme: tempUri.scheme,
128-
host: tempUri.host,
129-
path: "${tempUri.path}$keyEndPointLogin",
130-
queryParameters: {keyVarUsername: username, keyVarPassword: password});
131-
132-
final response = await _client.post(url, headers: {
133-
keyHeaderRevocableSession: "1",
134-
});
135-
136-
_handleResponse(response, ParseApiRQ.login);
137-
return this;
138-
} on Exception catch (e) {
139-
return _handleException(e, ParseApiRQ.login);
140-
}
44+
/// Handles any errors returned in response
45+
static ParseResponse _handleError(ParseResponse response, Response apiResponse) {
46+
Map<String, dynamic> responseData = JsonDecoder().convert(apiResponse.body);
47+
response.error = ParseError(code: responseData['code'], message: responseData['error']);
48+
response.statusCode = responseData['code'];
49+
return response;
14150
}
14251

143-
/// Removes the current user from the session data
144-
logout() {
145-
_client.data.sessionId = null;
146-
setObjectData(null);
52+
/// Handles successful responses with no results
53+
static ParseResponse _handleSuccessWithNoResults(ParseResponse response, int code, String value) {
54+
response.success = true;
55+
response.statusCode = 200;
56+
response.error = ParseError(code: code, message: value);
57+
return response;
14758
}
14859

149-
/// Sends a verification email to the users email address
150-
verificationEmailRequest() async {
151-
try {
152-
final response = await _client.post(
153-
"${_client.data.serverUrl}$keyEndPointVerificationEmail",
154-
body: json.encode({keyVarEmail: emailAddress}));
155-
return _handleResponse(response, ParseApiRQ.verificationEmailRequest);
156-
} on Exception catch (e) {
157-
return _handleException(e, ParseApiRQ.verificationEmailRequest);
158-
}
159-
}
60+
/// Handles successful response with results
61+
static ParseResponse _handleSuccess(ParseResponse response, dynamic object, String responseBody) {
62+
response.success = true;
16063

161-
/// Sends a password reset email to the users email address
162-
requestPasswordReset() async {
163-
try {
164-
final response = await _client.post(
165-
"${_client.data.serverUrl}$keyEndPointRequestPasswordReset",
166-
body: json.encode({keyVarEmail: emailAddress}));
167-
return _handleResponse(response, ParseApiRQ.requestPasswordReset);
168-
} on Exception catch (e) {
169-
return _handleException(e, ParseApiRQ.requestPasswordReset);
170-
}
171-
}
64+
var map = JsonDecoder().convert(responseBody) as Map;
17265

173-
/// Saves the current user
174-
///
175-
/// If changes are made to the current user, call save to sync them with
176-
/// Parse Server
177-
save() async {
178-
if (objectId == null) {
179-
return signUp();
66+
if (map != null && map.length == 1 && map.containsKey('results')) {
67+
response.result = _handleMultipleResults(object, map.entries.first.value);
18068
} else {
181-
try {
182-
var uri = _client.data.serverUrl + "$path/$objectId";
183-
var body = json.encode(toJson(forApiRQ: true), toEncodable: dateTimeEncoder);
184-
final response = await _client.put(uri, body: body);
185-
return _handleResponse(response, ParseApiRQ.save);
186-
} on Exception catch (e) {
187-
return _handleException(e, ParseApiRQ.save);
188-
}
189-
}
190-
}
191-
192-
/// Removes a user from Parse Server locally and online
193-
Future<ParseResponse> destroy() async {
194-
if (objectId != null) {
195-
try {
196-
final response = await _client.delete(
197-
_client.data.serverUrl + "$path/$objectId",
198-
headers: {keyHeaderSessionToken: _client.data.sessionId});
199-
return _handleResponse(response, ParseApiRQ.destroy);
200-
} on Exception catch (e) {
201-
return _handleException(e, ParseApiRQ.destroy);
202-
}
203-
}
204-
205-
return null;
206-
}
207-
208-
/// Gets a list of all users (limited return)
209-
static Future<ParseResponse> all() async {
210-
211-
var emptyUser = ParseUser(null, null, null);
212-
213-
try {
214-
final response = await ParseHTTPClient().get(
215-
"${ParseCoreData().serverUrl}/$path");
216-
217-
ParseResponse parseResponse = ParseResponse.handleResponse(emptyUser, response);
218-
219-
if (ParseCoreData().debug) {
220-
logger(ParseCoreData().appName, keyClassUser, ParseApiRQ.getAll.toString(), parseResponse);
221-
}
222-
223-
return parseResponse;
224-
} on Exception catch (e) {
225-
return ParseResponse.handleException(e);
226-
}
227-
}
228-
229-
static ParseUser _getUserFromLocalStore() {
230-
var userJson = ParseCoreData().getStore().getString(keyParseStoreUser);
231-
232-
if (userJson != null) {
233-
var userMap = JsonDecoder().convert(userJson);
234-
235-
if (userMap != null) {
236-
ParseCoreData().sessionId = userMap[keyParamSessionToken];
237-
return ParseUser.clone(userMap);
238-
}
69+
response.result = _handleSingleResult(object, map);
23970
}
24071

241-
return null;
72+
return response;
24273
}
24374

244-
/// Handles an API response and logs data if [bool] debug is enabled
245-
ParseResponse _handleException(Exception exception, ParseApiRQ type) {
246-
ParseResponse parseResponse = ParseResponse.handleException(exception);
75+
/// Handles a response with a multiple result object
76+
static _handleMultipleResults(dynamic object, dynamic map) {
77+
var resultsList = List();
24778

248-
if (_debug) {
249-
logger(ParseCoreData().appName, className, type.toString(), parseResponse);
79+
for (var value in map) {
80+
resultsList.add(_handleSingleResult(object, value));
25081
}
25182

252-
return parseResponse;
83+
return resultsList;
25384
}
25485

255-
/// Handles all the response data for this class
256-
_handleResponse(Response response, ParseApiRQ type) {
257-
258-
ParseResponse parseResponse = ParseResponse.handleResponse(this, response);
259-
if (_debug) {
260-
logger(ParseCoreData().appName, className, type.toString(), parseResponse);
261-
}
262-
263-
Map<String, dynamic> responseData = JsonDecoder().convert(response.body);
264-
if (responseData.containsKey(keyVarObjectId)) {
265-
fromJson(responseData);
266-
_client.data.sessionId = responseData[keyParamSessionToken];
267-
}
268-
269-
if (type == ParseApiRQ.getAll || type == ParseApiRQ.destroy) {
270-
return parseResponse;
271-
} else {
272-
saveInStorage(keyParseStoreUser);
273-
return this;
274-
}
86+
/// Handles a response with a single result object
87+
static _handleSingleResult(dynamic object, map) {
88+
if (object is Parse) return map;
89+
if (object is ParseCloneable) return object.clone(map);
90+
return null;
27591
}
27692
}

0 commit comments

Comments
 (0)