React Native
...
Users
Запросы и фильтрация пользователей в Parse для React Native
9 мин
запрос пользователей в parse на react native введение некоторым приложениям react native необходимо напрямую управлять пользователями вашего приложения или, по крайней мере, иметь возможность перечислять конкретный подмножество из них parse имеет мощные инструменты для запросов, и они также могут быть использованы для ваших пользователей в вашем приложении социальных сетей, например в этом руководстве вы узнаете, как использовать parse query parse query для выполнения реалистичных запросов пользователей в вашем приложении react native с использованием parse js sdk предварительные требования чтобы завершить этот учебник, вам потребуется приложение react native, созданное и подключенное к back4app цель создать функцию запроса пользователей с использованием parse для приложения react native 1 понимание класса parse query любая операция запроса parse использует тип объекта parse query parse query , который поможет вам извлекать конкретные данные из вашей базы данных на протяжении всего вашего приложения важно знать, что parse query parse query разрешится только после вызова метода извлечения (например, parse query find parse query find или parse query get parse query get ), поэтому запрос может быть настроен, и несколько модификаторов могут быть связаны перед фактическим вызовом чтобы создать новый parse query parse query , вам нужно передать в качестве параметра желаемый parse object parse object подкласс, который будет содержать результаты вашего запроса пример для этого случая использования в руководстве ( parse user parse user ) можно увидеть ниже javascript 1 // this will create your query 2 const parsequery = new parse query(parse user); 3 // the query will resolve only after calling this method 5 const queryresult = await parsequery find();1 // this will create your query 2 const parsequery parse query = new parse query(parse user); 3 // the query will resolve only after calling this method 4 const queryresult \[parse user] = await parsequery find(); вы можете узнать больше о классе parse query parse query здесь в официальной документации https //parseplatform org/parse sdk js/api/master/parse query html 2 выполнение соответствующих запросов пользователей теперь давайте рассмотрим некоторые соответствующие запросы, которые вам может понадобиться выполнить при управлении или отображении пользователей в вашем приложении прежде всего, давайте выполним текстовый поисковый запрос, ищущий пользователей, чьи имена пользователей содержат искомое значение javascript 1 const douserquery = async function () { 2 // this value comes from a state variable 3 const usernamesearchvalue = usernamesearch; 4 // this will create your user query 5 const parsequery = new parse query(parse user); 6 // several query functions can be set to your parse,query, they will 7 // only resolve when calling "find", for example 8 if (usernamesearchvalue !== '') { 9 // "contains" will retrieve users whose username contain the searched value, case sensitive 10 parsequery contains('username', usernamesearchvalue); 11 // 12 // or 13 // 14 // for case insensitive string search, use "matches", that will take into account 15 // an regexp for matching, in this case use only "i", which is the regexp modifier 16 // for case insensitive 17 parsequery matches('username', usernamesearchvalue, 'i'); 18 } 19 // only after calling "find" all query conditions will resolve 20 return await parsequery 21 find() 22 then(async (queriedusers => { 23 // set the query results to an state variable to retrieve it on your jsx 24 // be aware that empty or invalid queries return as an empty array 25 setqueryresults(queriedusers); 26 return true; 27 }) 28 catch((error) => { 29 // error can be caused by lack of internet connection, but in most 30 // cases "find" will return as an empty array on "then" 31 alert alert('error!', error message); 32 setqueryresults(\[]); 33 return false; 34 }); 35 };1 const douserquery = async function () promise\<boolean> { 2 // this value comes from a state variable 3 const usernamesearchvalue string = usernamesearch; 4 // this will create your user query 5 const parsequery parse query = new parse query(parse user); 6 // several query functions can be set to your parse,query, they will 7 // only resolve when calling "find", for example 8 if (usernamesearchvalue !== '') { 9 // "contains" will retrieve users whose username contain the searched value, case sensitive 10 parsequery contains('username', usernamesearchvalue); 11 // 12 // or 13 // 14 // for case insensitive string search, use "matches", that will take into account 15 // an regexp for matching, in this case use only "i", which is the regexp modifier 16 // for case insensitive 17 parsequery matches('username', usernamesearchvalue, 'i'); 18 } 19 // only after calling "find" all query conditions will resolve 20 return await parsequery 21 find() 22 then(async (queriedusers \[parse user]) => { 23 // set the query results to an state variable to retrieve it on your jsx 24 // be aware that empty or invalid queries return as an empty array 25 setqueryresults(queriedusers); 26 return true; 27 }) 28 catch((error object) => { 29 // error can be caused by lack of internet connection, but in most 30 // cases "find" will return as an empty array on "then" 31 alert alert('error!', error message); 32 setqueryresults(\[]); 33 return false; 34 }); 35 }; обратите внимание, что существует как минимум два разных способа поиска строки, каждый из которых имеет свои специфические применения и преимущества в большинстве случаев вы захотите использовать parse query matches parse query matches для обеспечения нечувствительных к регистру результатов и избежания неожиданных ошибок в вашем коде после выполнения этого запроса ваш список пользователей в приложении должен выглядеть примерно так в дополнение к строковому запросу вы также можете выполнять "точные" запросы, когда хотите получить объекты, содержащие точное значение, так же как и с булевыми полями следующий пример покажет, как получить пользователей, которые подтверждены по электронной почте, через поле emailverified emailverified javascript 1 const douserquery = async function () { 2 // this value comes from a state variable 3 const showonlyverifiedvalue boolean = showonlyverified; 4 // this will create your user query 5 const parsequery = new parse query(parse user); 6 // several query functions can be set to your parse,query, they will 7 // only resolve when calling "find", for example 8 if (showonlyverifiedvalue === true) { 9 // "equalto" will retrieve users whose "emailverified" value is exactly "true" 10 parsequery equalto('emailverified', true); 11 } 12 // only after calling "find" all query conditions will resolve 13 return await parsequery 14 find() 15 then(async (queriedusers) => { 16 // set the query results to an state variable to retrieve it on your jsx 17 // be aware that empty or invalid queries return as an empty array 18 setqueryresults(queriedusers); 19 return true; 20 }) 21 catch((error) => { 22 // error can be caused by lack of internet connection, but in most 23 // cases "find" will return as an empty array on "then" 24 alert alert('error!', error message); 25 setqueryresults(\[]); 26 return false; 27 }); 28 };1 const douserquery = async function () promise\<boolean> { 2 // this value comes from a state variable 3 const showonlyverifiedvalue boolean = showonlyverified; 4 // this will create your user query 5 const parsequery parse query = new parse query(parse user); 6 // several query functions can be set to your parse,query, they will 7 // only resolve when calling "find", for example 8 if (showonlyverifiedvalue === true) { 9 // "equalto" will retrieve users whose "emailverified" value is exactly "true" 10 parsequery equalto('emailverified', true); 11 } 12 // only after calling "find" all query conditions will resolve 13 return await parsequery 14 find() 15 then(async (queriedusers \[parse user]) => { 16 // set the query results to an state variable to retrieve it on your jsx 17 // be aware that empty or invalid queries return as an empty array 18 setqueryresults(queriedusers); 19 return true; 20 }) 21 catch((error object) => { 22 // error can be caused by lack of internet connection, but in most 23 // cases "find" will return as an empty array on "then" 24 alert alert('error!', error message); 25 setqueryresults(\[]); 26 return false; 27 }); 28 }; ваше приложение теперь должно обновлять список пользователей вот так другим распространенным примером будет применение сортировок к вашему запросу это можно сделать двумя способами, либо с помощью parse query ascending/parse query descending parse query ascending/parse query descending или parse query addascending/parse query adddescending parse query addascending/parse query adddescending в первом случае будет переопределена любая другая сортировка, и это будет единственное, что запрос примет, а во втором случае будет добавлено к существующим сортировкам, что сделает возможными множественные сортировки javascript 1 const douserquery = async function () { 2 // this value comes from a state variable 3 const orderbyvalue = orderby; 4 // this will create your user query 5 const parsequery = new parse query(parse user); 6 // several query functions can be set to your parse,query, they will 7 // only resolve when calling "find", for example 8 // for list ordering, you can use "addascending" or "adddescending", passing as parameter 9 // which object field should be the one to order by 10 // note that "usernameasc", "usernamedesc" and so on are made up string values applied to a filter in 11 // our example app, so change it by what is suitable to you 12 if (orderbyvalue === 'usernameasc') { 13 parsequery ascending('username'); 14 // 15 // or 16 // 17 parsequery addascending('username'); 18 } else if (orderbyvalue === 'usernamedesc') { 19 parsequery descending('username'); 20 // 21 // or 22 // 23 parsequery adddescending('username'); 24 } else if (orderbyvalue === 'dateasc') { 25 parsequery ascending('createdat'); 26 // 27 // or 28 // 29 parsequery addascending('createdat'); 30 } else if (orderbyvalue === 'datedesc') { 31 parsequery descending('createdat'); 32 // 33 // or 34 // 35 parsequery adddescending('createdat'); 36 } 37 // only after calling "find" all query conditions will resolve 38 return await parsequery 39 find() 40 then(async (queriedusers) => { 41 // set the query results to an state variable to retrieve it on your jsx 42 // be aware that empty or invalid queries return as an empty array 43 setqueryresults(queriedusers); 44 return true; 45 }) 46 catch((error) => { 47 // error can be caused by lack of internet connection, but in most 48 // cases "find" will return as an empty array on "then" 49 alert alert('error!', error message); 50 setqueryresults(\[]); 51 return false; 52 }); 53 };1 const douserquery = async function () promise\<boolean> { 2 // this value comes from a state variable 3 const orderbyvalue string = orderby; 4 // this will create your user query 5 const parsequery parse query = new parse query(parse user); 6 // several query functions can be set to your parse,query, they will 7 // only resolve when calling "find", for example 8 // for list ordering, you can use "addascending" or "adddescending", passing as parameter 9 // which object field should be the one to order by 10 // note that "usernameasc", "usernamedesc" and so on are made up string values applied to a filter in 11 // our example app, so change it by what is suitable to you 12 if (orderbyvalue === 'usernameasc') { 13 parsequery ascending('username'); 14 // 15 // or 16 // 17 parsequery addascending('username'); 18 } else if (orderbyvalue === 'usernamedesc') { 19 parsequery descending('username'); 20 // 21 // or 22 // 23 parsequery adddescending('username'); 24 } else if (orderbyvalue === 'dateasc') { 25 parsequery ascending('createdat'); 26 // 27 // or 28 // 29 parsequery addascending('createdat'); 30 } else if (orderbyvalue === 'datedesc') { 31 parsequery descending('createdat'); 32 // 33 // or 34 // 35 parsequery adddescending('createdat'); 36 } 37 // only after calling "find" all query conditions will resolve 38 return await parsequery 39 find() 40 then(async (queriedusers \[parse user]) => { 41 // set the query results to an state variable to retrieve it on your jsx 42 // be aware that empty or invalid queries return as an empty array 43 setqueryresults(queriedusers); 44 return true; 45 }) 46 catch((error object) => { 47 // error can be caused by lack of internet connection, but in most 48 // cases "find" will return as an empty array on "then" 49 alert alert('error!', error message); 50 setqueryresults(\[]); 51 return false; 52 }); 53 }; теперь ваше приложение должно упорядочивать ваши запросы следующим образом помните, что все ограничения запросов, упомянутые выше, могут быть связаны и выполнены в одном запросе, улучшая удобство вашего приложения для создания различных фильтров и сортировок, которые будут работать вместе вот полный код, представляющий все методы запросов, используемые в этом руководстве javascript 1 const douserquery = async function () { 2 // this value comes from a state variable 3 const usernamesearchvalue = usernamesearch; 4 const showonlyverifiedvalue = showonlyverified; 5 const orderbyvalue = orderby; 6 // this will create your user query 7 const parsequery = new parse query(parse user); 8 // several query functions can be set to your parse,query, they will 9 // only resolve when calling "find", for example 10 if (usernamesearchvalue !== '') { 11 // "contains" will retrieve users whose username contain the searched value, case sensitive 12 parsequery contains('username', usernamesearchvalue); 13 // 14 // or 15 // 16 // for case insensitive string search, use "matches", that will take into account 17 // an regexp for matching, in this case use only "i", which is the regexp modifier 18 // for case insensitive 19 parsequery matches('username', usernamesearchvalue, 'i'); 20 } 21 if (showonlyverifiedvalue === true) { 22 // "equalto" will retrieve users whose "emailverified" value is exactly "true" 23 parsequery equalto('emailverified', true); 24 } 25 // for list ordering, you can use "addascending" or "adddescending", passing as parameter 26 // which object field should be the one to order by 27 if (orderbyvalue === 'usernameasc') { 28 parsequery ascending('username'); 29 // 30 // or 31 // 32 parsequery addascending('username'); 33 } else if (orderbyvalue === 'usernamedesc') { 34 parsequery descending('username'); 35 // 36 // or 37 // 38 parsequery adddescending('username'); 39 } else if (orderbyvalue === 'dateasc') { 40 parsequery ascending('createdat'); 41 // 42 // or 43 // 44 parsequery addascending('createdat'); 45 } else if (orderbyvalue === 'datedesc') { 46 parsequery descending('createdat'); 47 // 48 // or 49 // 50 parsequery adddescending('createdat'); 51 } 52 // only after calling "find" all query conditions will resolve 53 return await parsequery 54 find() 55 then(async (queriedusers) => { 56 // set the query results to an state variable to retrieve it on your jsx 57 // be aware that empty or invalid queries return as an empty array 58 setqueryresults(queriedusers); 59 return true; 60 }) 61 catch((error) => { 62 // error can be caused by lack of internet connection, but in most 63 // cases "find" will return as an empty array on "then" 64 alert alert('error!', error message); 65 setqueryresults(\[]); 66 return false; 67 }); 68 };1 const douserquery = async function () promise\<boolean> { 2 // this value comes from a state variable 3 const usernamesearchvalue string = usernamesearch; 4 const showonlyverifiedvalue boolean = showonlyverified; 5 const orderbyvalue string = orderby; 6 // this will create your user query 7 const parsequery parse query = new parse query(parse user); 8 // several query functions can be set to your parse,query, they will 9 // only resolve when calling "find", for example 10 if (usernamesearchvalue !== '') { 11 // "contains" will retrieve users whose username contain the searched value, case sensitive 12 parsequery contains('username', usernamesearchvalue); 13 // 14 // or 15 // 16 // for case insensitive string search, use "matches", that will take into account 17 // an regexp for matching, in this case use only "i", which is the regexp modifier 18 // for case insensitive 19 parsequery matches('username', usernamesearchvalue, 'i'); 20 } 21 if (showonlyverifiedvalue === true) { 22 // "equalto" will retrieve users whose "emailverified" value is exactly "true" 23 parsequery equalto('emailverified', true); 24 } 25 // for list ordering, you can use "addascending" or "adddescending", passing as parameter 26 // which object field should be the one to order by 27 if (orderbyvalue === 'usernameasc') { 28 parsequery ascending('username'); 29 // 30 // or 31 // 32 parsequery addascending('username'); 33 } else if (orderbyvalue === 'usernamedesc') { 34 parsequery descending('username'); 35 // 36 // or 37 // 38 parsequery adddescending('username'); 39 } else if (orderbyvalue === 'dateasc') { 40 parsequery ascending('createdat'); 41 // 42 // or 43 // 44 parsequery addascending('createdat'); 45 } else if (orderbyvalue === 'datedesc') { 46 parsequery descending('createdat'); 47 // 48 // or 49 // 50 parsequery adddescending('createdat'); 51 } 52 // only after calling "find" all query conditions will resolve 53 return await parsequery 54 find() 55 then(async (queriedusers \[parse user]) => { 56 // set the query results to an state variable to retrieve it on your jsx 57 // be aware that empty or invalid queries return as an empty array 58 setqueryresults(queriedusers); 59 return true; 60 }) 61 catch((error object) => { 62 // error can be caused by lack of internet connection, but in most 63 // cases "find" will return as an empty array on "then" 64 alert alert('error!', error message); 65 setqueryresults(\[]); 66 return false; 67 }); 68 }; заключение в конце этого руководства вы узнали, как выполнять запросы к пользователям parse в react native в следующем руководстве мы покажем вам, как сохранять и читать данные в parse