当前位置:网站首页>Using cloud DB to build app quick start - quick application
Using cloud DB to build app quick start - quick application
2022-06-11 15:47:00 【Gauss squirrel Club】
Fast app data will be stored on the cloud side , Data is not cached locally . When performing data management operations , You will directly operate cloud side data . Apply it quickly SDK It will guarantee the communication and communication security between your application and cloud database .
Use Cloud DB Building fast applications , The following preparations need to be completed :
- You have registered your account on the official website of the developer alliance and passed the real name authentication , For details, see Account registration authentication .
- Complete the construction of the development environment , Included in PC Install fast app on IDE、 Install the fast application loader on the test mobile phone , For details, see Install development tools .
- stay AppGallery Connect Complete the creation of quick application on the console , For details, see Create fast apps .
- Use fast apps IDE Generate certificate thumbprint , And in AppGallery Connect Complete the fingerprint configuration on the console , For details, see Generate 、 Configure fingerprint certificate .
- You've got the sample code , Please from Sample code obtain .
Enable service
Use Cloud DB Before service , You need to enable the service first .
- Sign in AppGallery Connect Website , choice “ My project ”.
- Select the item in the item list page , Click the application that needs to enable cloud database service under the project .
- Select... From the navigation tree “ structure > Cloud database ”.
- single click “ Open now ”, Open Cloud database service .

- ( Optional ) If you have not selected a data processing location , You need to set the data processing location first , Please refer to Set the data processing location .

- After the service is initialized successfully , That is, the cloud database service is enabled successfully .
Add and export object types
You need to be based on AppGallery Connect Console creates object types , Please follow the steps to create the object types involved in the example , And export... For fast application development json Format and js Format object type file . It is not allowed to modify the exported json Format and js Format file , Otherwise, the data synchronization function will be abnormal .
- Sign in AppGallery Connect Website , choice “ My project ”.
- Select the item in the item list page , Click the application that needs to create the object type under the project .
- Select... From the navigation tree “ structure > Cloud database ”.
- single click “ newly added ”, Enter the create object type page .

- Enter an object type named “BookInfo” after , single click “ next step ”.
- single click
, After adding the following fields , single click “ next step ”.
surface 1 Field definition table Field name
type
Primary key
Non empty
encryption
The default value is
id
Integer
√
√
–
–
bookName
String
–
–
–
–
author
String
–
–
–
–
price
Double
–
–
–
–
publisher
String
–
–
–
–
publishTime
Date
–
–
–
–
shadowFlag
Boolean
–
–
–
true
- single click
, Set the index name to “bookName”, The index field is “bookName” after , single click “ next step ”.
- Set the permissions of each role according to the following requirements , single click “ next step ”.
surface 2 Permission configuration table role
query
upsert
delete
All the people
√
–
–
Authenticated user
√
√
√
Data creator
√
√
√
Administrators
√
√
√
- single click “ determine ”.
After creation, return to the object type list , You can view the object types that have been created .
- single click “ export ”.

- export “json Format ” and “js Format ” file , The exported file is used to add to the local development environment in subsequent steps .
- export json Format file
- choice “json Format ”.
- single click “ export ”.
- export js Format file
- choice “js Format ”.
- choice js file type , choice “js”.
- single click “ export ”.
- export json Format file
New storage area
You can be based on AppGallery Connect The console creates a data store on the cloud side , Please follow the steps to create a storage area named “QuickStartDemo” The storage area of .
- Sign in AppGallery Connect Website , choice “ My project ”.
- Select the item in the item list page , Click the application that needs to create a storage area under the project .
- Select... From the navigation tree “ structure > Cloud database ”.
- choice “ Storage area ” Tab .
- single click “ newly added ”, Enter the create storage page .

- The input store name is “QuickStartDemo”.
- single click “ determine ”.
After creation, return to the storage area list , You can view the created storage .
Configure the development environment
- Create a quick app project .
- Open the quick app IDE, On the welcome page, click login , Log in to the registered account in the jump page .
- After successful login ,IDE Navigation options for “ New project > Apply it quickly - Development of cloud ”, Select the associated application 、 Templates , After setting the project path , single click “ determine ”.
- Related applications : Before choosing AppGallery Connect Quick app created on .
- Project path : Deposit Serverless The path of project engineering .
The new project structure is mainly composed of quickapp.config.json、client、cloudfunctions form .
|-- client Used to store standard fast application code
|-- |-- src Standard fast application source code directory
|-- |-- |-- Common Quick application public resource file directory
|-- |-- |-- Hello Quick application home file directory
|-- |-- |-- app.ux Quick application entry file
|-- |-- |-- manifest.json Quick application profile
|-- |-- package.json Fast application code relies on cloud functions SDK Configuration file for
|-- cloudfunctions Cloud function Directory , Multiple cloud function directories can be created under this directory
|-- quickapp.config.json serverless The configuration file for the project

quickapp.config.json in the light of serverless The configuration information of the project is as follows :
- quickappRoot: Express client End fast application code directory , Apply it quickly serverless The project will only compile and package the contents in this directory .
- cloudfunctionRoot: Express serverless Project cloud function Directory , This directory mainly stores all cloud function codes of the project .
- Configure application information .
- Sign in AppGallery Connect Website , choice “ My project ”.
- Select the item in the item list page , Click apply... Under project .
- choice “ routine ” Tab , Download profile “agconnect-services.json”, And copy it to your quick app project src Under the table of contents .
- stay hello.ux Add... To the file agconnect-services.json File reference .
const context = require('../agconnect-services.json');
- Integrate Cloud DB SDK.
- Execute the following command , install Cloud DB JavaScript SDK Cloud database service module into your project .
npm install --save @agconnect/database - Import... Into your project database Components .
import "@agconnect/database";
- Execute the following command , install Cloud DB JavaScript SDK Cloud database service module into your project .
- stay manifest.json Of documents features Add the following configuration to the property .
{"name": "system.cipher"}
Add object type file
When developing applications , You can directly put AppGallery Connect Exported from the console json Format and js Add the format file to the local development environment , And pass AGConnectCloudDB Class createObjectType() Method to define and create object types . When you are developing local applications , There is no need to create the object type again .
- Will already be in AppGallery Connect All exported on the console json Format and js Add the format file to the local development environment .
- initialization Cloud DB, adopt AGConnectCloudDB Class createObjectType() Method to define and create object types , For details, see initialization .
initialization
After adding the object type file , You can use cloud database for application development . When you develop an application , You need to perform initialization first , initialization AGConnectCloudDB、 establish Cloud DB zone And object types .
- adopt initialize() initialization AGConnectCloudDB.
AGConnectCloudDB.initialize(context); - adopt getInstance() Method to get AGConnectCloudDB example , And use createObjectType() Create object type .
const schema = require('./BookInfo.json'); agcCloudDB = AGConnectCloudDB.getInstance(); agcCloudDB.createObjectType(schema); - open Cloud DB zone.
const config = new CloudDBZoneConfig('QuickStartDemo'); cloudDBZone = await agcCloudDB.openCloudDBZone(config);
Write data
This section mainly introduces how to write data in the application , As shown below , Use executeUpsert() Realize data writing .
async function executeUpsert (book) {
try {
const cloudDBZoneResult = await cloudDBZone.executeUpsert(book);
console.log('upsert' + cloudDBZoneResult + 'record' );
} catch (e) {
console.log('upsert failed with reason');
conso.log(e);
}
}View the data
Get data changes
Data added by the user in the application interface , Will be stored on the cloud side . Register the data change listener on the end side , When the cloud side data changes , The end side can sense data changes . Through the query criteria and subscribeSnapshot() Method combination , You can specify the listening object , When the data of the listening object changes , The end side will receive the data change notification , And generate a new snapshot , Trigger user callback .
async function subscribeSnapshot () {
const query = CloudDBZoneQuery.where(BookInfo);
query.equalTo('shadowFlag', true);
try {
const onSnapshotListener = {
onSnapshot: (snapshot, e) => {
if (e !== null && e !== undefined && e.code !== AGConnectCloudDBExceptionCode.Ok) {
console.log('subscribeSnapshot error');
console.log(e);
}
return snapshot.getSnapshotObjects();
}
};
const listenerHandler = await cloudDBZone.subscribeSnapshot(query, onSnapshotListener);
console.log(listenerHandler);
} catch (e) {
console.log('subscribeSnapshot error');
console.log(e);
return null;
}
}
function subscribeBookList() {
subscribeSnapshot().then(snapshot => {
snapshot.getDeletedObjects();
const resultList = snapshot.getSnapshotObjects();
console.log(resultList);
})
}Data query and sorting
adopt executeQuery() Realize asynchronous query of data .
async function executeQuery() {
try {
const query = CloudDBZoneQuery.where(BookInfo);
const snapshot = await cloudDBZone.executeQuery(query);
const resultArray = snapshot.getSnapshotObjects();
console.log(resultArray);
} catch(e) {
console.log(e);
}
}Through query and limit() Method combination , Realize the function of limiting the number of query data display ; And orderByAsc() Methods or orderByDesc() Method combination to realize the sorting function of data .
async function executeQueryWithOrder (object) {
const query = CloudDBZoneQuery.where(BookInfo);
if (object.name.length > 0) {
query.equalTo('bookName', object.name);
}
if (parseFloat(object.minPrice) > 0) {
query.greaterThanOrEqualTo('price', parseFloat(object.minPrice));
}
if (parseFloat(object.maxPrice) > 0 && parseFloat(object.maxPrice) > parseFloat(object.minPrice)) {
query.lessThanOrEqualTo('price', parseFloat(object.maxPrice));
}
if (parseInt(object.bookCount) > 0) {
query.limit(parseInt(object.bookCount));
}
query.orderByAsc('id');
try {
const snapshot = await cloudDBZone.executeQuery(query);
console.log('resultArray');
console.log(snapshot.getSnapshotObjects());
return snapshot.getSnapshotObjects();
} catch (e) {
console.log('query failed with reason');
console.log(e);
}
}边栏推荐
- 前沿科技探究DeepSQL:库内AI算法
- 让快递快到来不及退款的,真的不是人
- Introduction and use of etcd
- 调代码最离谱错误合集
- Kaixia was selected into the 2022 global top 100 innovation institutions list of Kerui Weian
- 【愚公系列】2022年06月 .NET架构班 078-分布式中间件 ScheduleMaster的Worker集群
- Export configuration to FTP or TFTP server
- 泰雷兹云安全报告显示,云端数据泄露和复杂程度呈上升趋势
- 如何预测SQL语句查询时间?
- [creation mode] builder mode
猜你喜欢

拿到20K我用了5年,面了所有大厂,这些高频面试问题都帮你们划出来啦

【愚公系列】2022年06月 .NET架构班 078-分布式中间件 ScheduleMaster的Worker集群

Google Earth engine (GEE) - create a simple panel demo to display the map

Go language - array

openGauss并行解码浅谈

Performance of MOS transistor 25n120 of asemi in different application scenarios

从屡遭拒稿到90后助理教授,罗格斯大学王灏:好奇心驱使我不断探索

dapr 思维导图

Devil cold rice # 037 devil shares the ways to become a big enterprise; Female anchor reward routine; Self discipline means freedom; Interpretation of simple interest and compound interest
![[0006] title, keyword and page description](/img/28/973bdb04420c9e6e9a2331663c6948.png)
[0006] title, keyword and page description
随机推荐
【MongoDB】4. Usage specification of mongodb
测试9年,面试华为要薪1万,华为员工:公司没这么低工资的岗
Maui introductory tutorial series (1. framework introduction)
Interview shock 26: how to stop threads correctly?
【0006】title、关键字及页面描述
Why are bugs changing more and more?
Devil cold rice # 037 devil shares the ways to become a big enterprise; Female anchor reward routine; Self discipline means freedom; Interpretation of simple interest and compound interest
硬核分析懒汉式单例
Failed to create pod sandbox: rpc error: code = Unknown desc = [failed to set up sandbox container..
JVM基础概念入门
Failed to create pod sandbox: rpc error: code = Unknown desc = [failed to set up sandbox container..
【愚公系列】2022年06月 .NET架构班 077-分布式中间件 ScheduleMaster加载程序集定时任务
Shuttle-- common commands
IDEA2021.1版本安装教程
容易让单片机程序跑飞的原因
实时特征计算平台架构方法论和实践
【创建型模式】抽象工厂模式
ASEMI的MOS管24N50参数,24N50封装,24N50尺寸
selenium--显示等待(中)--详解篇
Verification code is the natural enemy of automation? Ali developed a solution





