当前位置:网站首页>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 .

  1. Sign in AppGallery Connect Website , choice “ My project ”.
  2. Select the item in the item list page , Click the application that needs to enable cloud database service under the project .
  3. Select... From the navigation tree “ structure > Cloud database ”.
  4. single click “ Open now ”, Open Cloud database service .

  5. ( 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 .

  6. 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 .

  1. Sign in AppGallery Connect Website , choice “ My project ”.
  2. Select the item in the item list page , Click the application that needs to create the object type under the project .
  3. Select... From the navigation tree “ structure > Cloud database ”.
  4. single click “ newly added ”, Enter the create object type page .

  5. Enter an object type named “BookInfo” after , single click “ next step ”.
  6. 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

  7. single click

    , Set the index name to “bookName”, The index field is “bookName” after , single click “ next step ”.
  8. 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

  9. single click “ determine ”.

    After creation, return to the object type list , You can view the object types that have been created .

  10. single click “ export ”.

  11. 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
      1. choice “json Format ”.
      2. single click “ export ”.
    • export js Format file
      1. choice “js Format ”.
      2. choice js file type , choice “js”.
      3. single click “ export ”.

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 .

  1. Sign in AppGallery Connect Website , choice “ My project ”.
  2. Select the item in the item list page , Click the application that needs to create a storage area under the project .
  3. Select... From the navigation tree “ structure > Cloud database ”.
  4. choice “ Storage area ” Tab .
  5. single click “ newly added ”, Enter the create storage page .

  6. The input store name is “QuickStartDemo”.
  7. single click “ determine ”.

    After creation, return to the storage area list , You can view the created storage .

Configure the development environment

  1. Create a quick app project .
    1. Open the quick app IDE, On the welcome page, click login , Log in to the registered account in the jump page .
    2. 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 .
  2. Configure application information .
    1. Sign in AppGallery Connect Website , choice “ My project ”.
    2. Select the item in the item list page , Click apply... Under project .
    3. choice “ routine ” Tab , Download profile “agconnect-services.json”, And copy it to your quick app project src Under the table of contents .
    4. stay hello.ux Add... To the file agconnect-services.json File reference .
      const context = require('../agconnect-services.json');

  3. Integrate Cloud DB SDK.
    1. Execute the following command , install Cloud DB JavaScript SDK Cloud database service module into your project .
      npm install --save @agconnect/database

    2. Import... Into your project database Components .
      import "@agconnect/database";
  4. 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 .

  1. Will already be in AppGallery Connect All exported on the console json Format and js Add the format file to the local development environment .
  2. 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 .

  1. adopt initialize() initialization AGConnectCloudDB.
    AGConnectCloudDB.initialize(context);

  2. adopt getInstance() Method to get AGConnectCloudDB example , And use createObjectType() Create object type .
    const schema = require('./BookInfo.json');
    agcCloudDB = AGConnectCloudDB.getInstance();
    agcCloudDB.createObjectType(schema);

  3. 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);
    }
}

原网站

版权声明
本文为[Gauss squirrel Club]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111535104858.html