Using Cloud Function validators in a React Native App
Introduction
In this guide, you will learn how to use the Parse Cloud Code function validators and context usage from a React Native App. You will see examples of validators implemented in cloud functions, how to use context between different functions, and also check how to implement a React Native component using these improved functions in Back4App.
Prerequisites
To complete this tutorial, you will need:
- A React Native App created and connected to Back4App.
- Understand how to deploy a cloud function on Back4App.
- If you want to run this guide’s example application, you should set up the
react-native-paper
library.
Goal
Run Parse Cloud Code functions with validators and context usage on Back4App from a React Native App.
Step 1 - Understanding Cloud Code Functions Validators
Using Cloud Code functions
in your application enables great flexibility in your code, making it possible to detach reusable methods from your app and to better control their behavior. You can check or review how to use them in our Cloud functions starter guide.
Data sent to these cloud functions must be validated to avoid unexpected errors, and Parse Cloud Code (starting from version 4.4.0) offers complete integrated validators
, that can be passed as an object
or even another function. These tests are called before executing any code inside your function, so you can always assume that data will be valid if the validators accept it.
Take the following cloud function as an example, in which the average of a certain movie rating is calculated. The movie name is required(movie
), so you can use the following object to ensure it is passed. If the movie parameter is not passed, the function will return an error containing the message “Validation failed. Please specify data for the movie.”.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Parse.Cloud.define('getMovieAverageRating', async (request) => {
const query = new Parse.Query("Review");
query.equalTo("movie", request.params.movie);
const results = await query.find();
let sum = 0;
for (let review of results) {
sum += review.get("rate");
}
return {
result: sum / results.length,
};
},{
fields : ['movie'],
});
You can also pass more advanced options to the validator
, such as requiring that the user calling the function is authenticated using the requireUser
flag. Another useful addition is to add a condition to validate a parameter value, such as the following, ensuring that the movie
value is a string and at least 3 characters long.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Parse.Cloud.define('getMovieAverageRating', async (request) => {
const query = new Parse.Query("Review");
query.equalTo("movie", request.params.movie);
const results = await query.find();
let sum = 0;
for (let review of results) {
sum += review.get("rate");
}
return {
result: sum / results.length,
};
},{
fields : {
movie : {
required: true,
type: String,
options: val => {
return val.length >= 3;
},
error: 'Movie must have at least 3 characters'
}
},
});
The complete list of validation
options can be seen on the Parse docs.
Step 2 - Understanding Cloud Code Functions Context
When using Cloud Code (starting from version 4.3.0) save triggers in your application, you can pass a context
dictionary in the Parse.Object.save
method and also pass it from a beforeSave
handler to an afterSave
handler. This can be used to ensure data consistency or to perform any kind of asynchronous operation doable only after successfully saving your object.
Take the following cloud function trigger as an example, in which a Review
object is saved and we want to differentiate whether the object save call was made from your application or the dashboard. This will be achieved by setting the context before saving the object in your app code like this:
1
2
3
4
5
6
7
const Review = new Parse.Object('Review');
Review.set('text', 'Great movie!');
Review.set('rate', 5);
Review.set('movie', 'Mission Very Possible');
const context = { fromApplication: true };
const savedReview = await Review.save(null, {context: context});
Here are the save trigger functions, note that the context object can be directly accessed from the request in both of them:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Parse.Cloud.beforeSave('Review', async (request) => {
// Try to get context
try {
const context = request.context;
if (context.fromApplication === true) {
// Set a flag in the object before saving
request.object.set('fromApplication', true);
}
} catch(error){}
const text = request.object.get('text');
if (text.length > 20) {
// Truncate and add a ...
request.object.set('text', text.substring(0, 17) + '...');
}
});
Parse.Cloud.afterSave('Review', async (request) => {
// Try to get context
try {
const context = request.context;
if (context.fromApplication === true) {
// Do something when coming from application, like sending a notification or email
console.log('Got context fromApplication when saving Review object');
}
} catch(error){}
});
Step 3 - Using Validated Cloud Code from a React Native component
Let’s now use the same component example from the last guide as a base and add some changes to highlight the functions now using validators and context. Remember to deploy the cloud functions shown in Steps 1 and 2 and, after that, change the “Review” object creation function to the following, with the addition of the context argument in the save method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const createReview = async function () {
try {
// This values come from state variables linked to
// the screen form fields
const reviewTextValue = reviewText;
const reviewRateValue = Number(reviewRate);
// Creates a new parse object instance
let Review = new Parse.Object('Review');
// Set data to parse object
// Simple title field
Review.set('text', reviewTextValue);
// Simple number field
Review.set('rate', reviewRateValue);
// Set default movie
Review.set('movie', 'Mission Very Possible');
// After setting the values, save it on the server
try {
// Add
const context = {fromApplication: true};
await Review.save(null, {context: context});
// Success
Alert.alert('Success!');
// Updates query result list
doReviewQuery();
runGetMovieAverageRating();
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
Alert.alert('Error!', error.message);
return false;
}
} catch (error) {
// Error can be caused by lack of field values
Alert.alert('Error!', error.message);
return false;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const createReview = async function (): Promise<boolean> {
try {
// This values come from state variables linked to
// the screen form fields
const reviewTextValue: string = reviewText;
const reviewRateValue: number = Number(reviewRate);
// Creates a new parse object instance
let Review: Parse.Object = new Parse.Object('Review');
// Set data to parse object
// Simple title field
Review.set('text', reviewTextValue);
// Simple number field
Review.set('rate', reviewRateValue);
// Set default movie
Review.set('movie', 'Mission Very Possible');
// After setting the values, save it on the server
try {
const context = {fromApplication: true};
await Review.save(null, {context: context});
// Success
Alert.alert('Success!');
// Updates query result list
doReviewQuery();
runGetMovieAverageRating();
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
Alert.alert('Error!', error.message);
return false;
}
} catch (error) {
// Error can be caused by lack of field values
Alert.alert('Error!', error.message);
return false;
}
};
To highlight the movie average calculation function validator, add a new function querying a movie called “Me” and add another button calling it. Remember that our validator will make the request fail because of the movie name length. Here is the new function code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const createReview = async function () {
try {
// This values come from state variables linked to
// the screen form fields
const reviewTextValue = reviewText;
const reviewRateValue = Number(reviewRate);
// Creates a new parse object instance
let Review = new Parse.Object('Review');
// Set data to parse object
// Simple title field
Review.set('text', reviewTextValue);
// Simple number field
Review.set('rate', reviewRateValue);
// Set default movie
Review.set('movie', 'Mission Very Possible');
// After setting the values, save it on the server
try {
// Add
const context = {fromApplication: true};
await Review.save(null, {context: context});
// Success
Alert.alert('Success!');
// Updates query result list
doReviewQuery();
runGetMovieAverageRating();
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
Alert.alert('Error!', error.message);
return false;
}
} catch (error) {
// Error can be caused by lack of field values
Alert.alert('Error!', error.message);
return false;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const createReview = async function (): Promise<boolean> {
try {
// This values come from state variables linked to
// the screen form fields
const reviewTextValue: string = reviewText;
const reviewRateValue: number = Number(reviewRate);
// Creates a new parse object instance
let Review: Parse.Object = new Parse.Object('Review');
// Set data to parse object
// Simple title field
Review.set('text', reviewTextValue);
// Simple number field
Review.set('rate', reviewRateValue);
// Set default movie
Review.set('movie', 'Mission Very Possible');
// After setting the values, save it on the server
try {
const context = {fromApplication: true};
await Review.save(null, {context: context});
// Success
Alert.alert('Success!');
// Updates query result list
doReviewQuery();
runGetMovieAverageRating();
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
Alert.alert('Error!', error.message);
return false;
}
} catch (error) {
// Error can be caused by lack of field values
Alert.alert('Error!', error.message);
return false;
}
};
This is how the new full component code is laid out, note that there is a new line in the listing item’s title showing if the Review was created from the application or not:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import React, {useState} from 'react';
import {Alert, Image, View, ScrollView, StyleSheet} from 'react-native';
import Parse from 'parse/react-native';
import {
List,
Title,
TextInput as PaperTextInput,
Button as PaperButton,
Text as PaperText,
} from 'react-native-paper';
export const MovieRatings = () => {
// State variable
const [queryResults, setQueryResults] = useState(null);
const [ratingsAverage, setRatingsAverage] = useState('');
const [reviewText, setReviewText] = useState('');
const [reviewRate, setReviewRate] = useState('');
const runGetMovieAverageRating = async function () {
try {
const params = {
movie: 'Mission Very Possible',
};
let resultObject = await Parse.Cloud.run(
'getMovieAverageRating',
params,
);
// Set query results to state variable using state hook
setRatingsAverage(resultObject.result.toFixed(1));
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
// or by not having an valid Review object yet
Alert.alert(
'Error!',
'Make sure that the cloud function is deployed and that the Review class table is created',
);
return false;
}
};
const runGetMeMovieAverageRating = async function () {
try {
const params = {
movie: 'Me',
};
let resultObject = await Parse.Cloud.run(
'getMovieAverageRating',
params,
);
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
// or by not having an valid Review object yet
Alert.alert('Error!', JSON.stringify(error.message));
return false;
}
};
const doReviewQuery = async function () {
// Create our query
let parseQuery = new Parse.Query('Review');
try {
let results = await parseQuery.find();
// Set query results to state variable
setQueryResults(results);
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
Alert.alert('Error!', error.message);
return false;
}
};
const createReview = async function () {
try {
// This values come from state variables linked to
// the screen form fields
const reviewTextValue = reviewText;
const reviewRateValue = Number(reviewRate);
// Creates a new parse object instance
let Review = new Parse.Object('Review');
// Set data to parse object
// Simple title field
Review.set('text', reviewTextValue);
// Simple number field
Review.set('rate', reviewRateValue);
// Set default movie
Review.set('movie', 'Mission Very Possible');
// After setting the values, save it on the server
try {
const context = {fromApplication: true};
await Review.save(null, {context: context});
// Success
Alert.alert('Success!');
// Updates query result list
doReviewQuery();
runGetMovieAverageRating();
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
Alert.alert('Error!', error.message);
return false;
}
} catch (error) {
// Error can be caused by lack of field values
Alert.alert('Error!', error.message);
return false;
}
};
return (
<>
<View style={Styles.header}>
<Image
style={Styles.header_logo}
source={ {uri: 'https://blog.back4app.com/wp-content/uploads/2019/05/back4app-white-logo-500px.png',} }
/>
<PaperText style={Styles.header_text}>
<PaperText style={Styles.header_text_bold}>
{'React Native on Back4App - '}
</PaperText>
{' Cloud Code Movie Ratings'}
</PaperText>
</View>
<ScrollView style={Styles.wrapper}>
<View>
<Title>{'Mission Very Possible Reviews'}</Title>
<PaperText>{`Ratings Average: ${ratingsAverage}`}</PaperText>
{/* Query list */}
{queryResults !== null &&
queryResults !== undefined &&
queryResults.map((result) => (
<List.Item
key={result.id}
title={`Review text: ${result.get('text')}`}
description={`Rate: ${result.get('rate')}\nFrom app: ${
result.get('fromApplication') !== undefined ? 'Yes' : 'No'
}`}
titleStyle={Styles.list_text}
style={Styles.list_item}
/>
))}
{queryResults === null ||
queryResults === undefined ||
(queryResults !== null &&
queryResults !== undefined &&
queryResults.length <= 0) ? (
<PaperText>{'No results here!'}</PaperText>
) : null}
</View>
<View>
<Title>Action Buttons</Title>
<PaperButton
onPress={() => runGetMovieAverageRating()}
mode="contained"
icon="search-web"
color={'#208AEC'}
style={Styles.list_button}>
{'Calculate Review Average'}
</PaperButton>
<PaperButton
onPress={() => runGetMeMovieAverageRating()}
mode="contained"
icon="search-web"
color={'#208AEC'}
style={Styles.list_button}>
{'Calculate Me Movie Review Average'}
</PaperButton>
<PaperButton
onPress={() => doReviewQuery()}
mode="contained"
icon="search-web"
color={'#208AEC'}
style={Styles.list_button}>
{'Query Reviews'}
</PaperButton>
</View>
<View>
<Title>Add new review</Title>
<PaperTextInput
value={reviewText}
onChangeText={text => setReviewText(text)}
label="Text"
mode="outlined"
style={Styles.form_input}
/>
<PaperTextInput
value={reviewRate}
onChangeText={text => setReviewRate(text)}
keyboardType={'number-pad'}
label="Rate (1-5)"
mode="outlined"
style={Styles.form_input}
/>
<PaperButton
onPress={() => createReview()}
mode="contained"
icon="plus"
style={Styles.submit_button}>
{'Add'}
</PaperButton>
</View>
</ScrollView>
</>
);
};
// These define the screen component styles
const Styles = StyleSheet.create({
header: {
alignItems: 'center',
paddingTop: 30,
paddingBottom: 50,
backgroundColor: '#208AEC',
},
header_logo: {
height: 50,
width: 220,
resizeMode: 'contain',
},
header_text: {
marginTop: 15,
color: '#f0f0f0',
fontSize: 16,
},
header_text_bold: {
color: '#fff',
fontWeight: 'bold',
},
wrapper: {
width: '90%',
alignSelf: 'center',
},
list_button: {
marginTop: 6,
marginLeft: 15,
height: 40,
},
list_item: {
borderBottomWidth: 1,
borderBottomColor: 'rgba(0, 0, 0, 0.12)',
},
list_text: {
fontSize: 15,
},
form_input: {
height: 44,
marginBottom: 16,
backgroundColor: '#FFF',
fontSize: 14,
},
submit_button: {
width: '100%',
maxHeight: 50,
alignSelf: 'center',
backgroundColor: '#208AEC',
},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import React, {FC, ReactElement, useState} from 'react';
import {Alert, Image, View, ScrollView, StyleSheet} from 'react-native';
import Parse from 'parse/react-native';
import {
List,
Title,
TextInput as PaperTextInput,
Button as PaperButton,
Text as PaperText,
} from 'react-native-paper';
export const MovieRatings: FC<{}> = ({}): ReactElement => {
// State variable
const [queryResults, setQueryResults] = useState(null);
const [ratingsAverage, setRatingsAverage] = useState('');
const [reviewText, setReviewText] = useState('');
const [reviewRate, setReviewRate] = useState('');
const runGetMovieAverageRating = async function (): Promise<boolean> {
try {
const params: {movie: string} = {
movie: 'Mission Very Possible',
};
let resultObject: {result: number} = await Parse.Cloud.run(
'getMovieAverageRating',
params,
);
// Set query results to state variable using state hook
setRatingsAverage(resultObject.result.toFixed(1));
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
// or by not having an valid Review object yet
Alert.alert(
'Error!',
'Make sure that the cloud function is deployed and that the Review class table is created',
);
return false;
}
};
const runGetMeMovieAverageRating = async function (): Promise<boolean> {
try {
const params: {movie: string} = {
movie: 'Me',
};
let resultObject: object = await Parse.Cloud.run(
'getMovieAverageRating',
params,
);
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
// or by not having an valid Review object yet
Alert.alert('Error!', JSON.stringify(error.message));
return false;
}
};
const doReviewQuery = async function (): Promise<boolean> {
// Create our query
let parseQuery: Parse.Query = new Parse.Query('Review');
try {
let results: [Parse.Object] = await parseQuery.find();
// Set query results to state variable
setQueryResults(results);
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
Alert.alert('Error!', error.message);
return false;
}
};
const createReview = async function (): Promise<boolean> {
try {
// This values come from state variables linked to
// the screen form fields
const reviewTextValue: string = reviewText;
const reviewRateValue: number = Number(reviewRate);
// Creates a new parse object instance
let Review: Parse.Object = new Parse.Object('Review');
// Set data to parse object
// Simple title field
Review.set('text', reviewTextValue);
// Simple number field
Review.set('rate', reviewRateValue);
// Set default movie
Review.set('movie', 'Mission Very Possible');
// After setting the values, save it on the server
try {
const context = {fromApplication: true};
await Review.save(null, {context: context});
// Success
Alert.alert('Success!');
// Updates query result list
doReviewQuery();
runGetMovieAverageRating();
return true;
} catch (error) {
// Error can be caused by lack of Internet connection
Alert.alert('Error!', error.message);
return false;
}
} catch (error) {
// Error can be caused by lack of field values
Alert.alert('Error!', error.message);
return false;
}
};
return (
<>
<View style={Styles.header}>
<Image
style={Styles.header_logo}
source={ {
uri:
'https://blog.back4app.com/wp-content/uploads/2019/05/back4app-white-logo-500px.png',
} }
/>
<PaperText style={Styles.header_text}>
<PaperText style={Styles.header_text_bold}>
{'React Native on Back4App - '}
</PaperText>
{' Cloud Code Movie Ratings'}
</PaperText>
</View>
<ScrollView style={Styles.wrapper}>
<View>
<Title>{'Mission Very Possible Reviews'}</Title>
<PaperText>{`Ratings Average: ${ratingsAverage}`}</PaperText>
{/* Query list */}
{queryResults !== null &&
queryResults !== undefined &&
queryResults.map((result: Parse.Object) => (
<List.Item
key={result.id}
title={`Review text: ${result.get('text')}`}
description={`Rate: ${result.get('rate')}\nFrom app: ${
result.get('fromApplication') !== undefined ? 'Yes' : 'No'
}`}
titleStyle={Styles.list_text}
style={Styles.list_item}
/>
))}
{queryResults === null ||
queryResults === undefined ||
(queryResults !== null &&
queryResults !== undefined &&
queryResults.length <= 0) ? (
<PaperText>{'No results here!'}</PaperText>
) : null}
</View>
<View>
<Title>Action Buttons</Title>
<PaperButton
onPress={() => runGetMovieAverageRating()}
mode="contained"
icon="search-web"
color={'#208AEC'}
style={Styles.list_button}>
{'Calculate Review Average'}
</PaperButton>
<PaperButton
onPress={() => runGetMeMovieAverageRating()}
mode="contained"
icon="search-web"
color={'#208AEC'}
style={Styles.list_button}>
{'Calculate Me Movie Review Average'}
</PaperButton>
<PaperButton
onPress={() => doReviewQuery()}
mode="contained"
icon="search-web"
color={'#208AEC'}
style={Styles.list_button}>
{'Query Reviews'}
</PaperButton>
</View>
<View>
<Title>Add new review</Title>
<PaperTextInput
value={reviewText}
onChangeText={text => setReviewText(text)}
label="Text"
mode="outlined"
style={Styles.form_input}
/>
<PaperTextInput
value={reviewRate}
onChangeText={text => setReviewRate(text)}
keyboardType={'number-pad'}
label="Rate (1-5)"
mode="outlined"
style={Styles.form_input}
/>
<PaperButton
onPress={() => createReview()}
mode="contained"
icon="plus"
style={Styles.submit_button}>
{'Add'}
</PaperButton>
</View>
</ScrollView>
</>
);
};
// These define the screen component styles
const Styles = StyleSheet.create({
header: {
alignItems: 'center',
paddingTop: 30,
paddingBottom: 50,
backgroundColor: '#208AEC',
},
header_logo: {
height: 50,
width: 220,
resizeMode: 'contain',
},
header_text: {
marginTop: 15,
color: '#f0f0f0',
fontSize: 16,
},
header_text_bold: {
color: '#fff',
fontWeight: 'bold',
},
wrapper: {
width: '90%',
alignSelf: 'center',
},
list_button: {
marginTop: 6,
marginLeft: 15,
height: 40,
},
list_item: {
borderBottomWidth: 1,
borderBottomColor: 'rgba(0, 0, 0, 0.12)',
},
list_text: {
fontSize: 15,
},
form_input: {
height: 44,
marginBottom: 16,
backgroundColor: '#FFF',
fontSize: 14,
},
submit_button: {
width: '100%',
maxHeight: 50,
alignSelf: 'center',
backgroundColor: '#208AEC',
},
});
This is how the component should look like after rendering and querying by one of the query functions:
Conclusion
At the end of this guide, you learned how to use Parse Cloud Code function validators and context. In the next guide, you will learn how to work with Users in Parse.