未验证 提交 845959f9 编写于 作者: O openharmony_ci 提交者: Gitee

!12458 [翻译完成】#I5WO3F

Merge pull request !12458 from Annie_wang/PR10840
......@@ -6,20 +6,20 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs
For details about the APIs, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis-distributedKVStore.md).
**Table 1** APIs provided by the DDS
| API | Description |
| ------------------------------------------------------------ | ----------------------------------------------- |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains a KV store with the specified **Options** and **storeId**.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. |
| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string,number]&gt;&gt;): void | Subscribes to data changes in the KV store. |
| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KvManager** object for database management. |
| getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. |
| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string,number]&gt;&gt;): void | Subscribes to data changes in the KV store. |
| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
## How to Develop
......@@ -28,23 +28,25 @@ The following uses a single KV store as an example to describe the development p
1. Import the distributed data module.
```js
import distributedData from '@ohos.data.distributedData';
import distributedKVStore from '@ohos.data.distributedKVStore';
```
2. Apply for the required permission if data synchronization is required.
Add the permission required (FA model) in the **config.json** file. The sample code is as follows:
```json
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
```
For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model).
This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
......@@ -52,7 +54,7 @@ The following uses a single KV store as an example to describe the development p
```js
// FA model
import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() {
console.info('grantPermission');
let context = featureAbility.getContext();
......@@ -62,21 +64,21 @@ The following uses a single KV store as an example to describe the development p
console.info('failed: ${error}');
})
}
grantPermission();
// Stage model
import Ability from '@ohos.application.Ability';
let context = null;
function grantPermission() {
class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
let context = this.context;
}
}
let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.log('success: ${data}');
......@@ -84,14 +86,14 @@ The following uses a single KV store as an example to describe the development p
console.log('failed: ${error}');
});
}
grantPermission();
```
3. Create a **kvManager** instance based on the specified **kvManagerConfig** object.
3. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **kvManagerConfig** object based on the application context.
2. Create a **kvManager** instance.
2. Create a **KvManager** instance.
The sample code is as follows:
......@@ -99,7 +101,7 @@ The following uses a single KV store as an example to describe the development p
// Obtain the context of the FA model.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
// Obtain the context of the stage model.
import AbilityStage from '@ohos.application.Ability';
let context = null;
......@@ -108,27 +110,23 @@ The following uses a single KV store as an example to describe the development p
context = this.context;
}
}
let kvManager;
try {
const kvManagerConfig = {
bundleName: 'com.example.datamanagertest',
userInfo: {
context:context,
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
context:context,
}
distributedData.createKVManager(kvManagerConfig, function (err, manager) {
distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) {
if (err) {
console.log('Failed to create KVManager: ${error}');
console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`);
return;
}
console.log('Created KVManager successfully');
kvManager = manager;
});
} catch (e) {
console.log('An unexpected error occurred. Error: ${e}');
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```
......@@ -147,34 +145,38 @@ The following uses a single KV store as an example to describe the development p
encrypt: false,
backup: false,
autoSync: false,
kvStoreType: distributedData.KVStoreType.SINGLE_VERSION,
securityLevel: distributedData.SecurityLevel.S0
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
securityLevel: distributedKVStore.SecurityLevel.S1
};
kvManager.getKVStore('storeId', options, function (err, store) {
if (err) {
console.log('Failed to get KVStore: ${err}');
console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`);
return;
}
console.log('Got KVStore successfully');
console.log('Obtained KVStore successfully');
kvStore = store;
});
} catch (e) {
console.log('An unexpected error occurred. Error: ${e}');
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```
> **NOTE**<br>
>
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
5. Subscribe to changes in the distributed data.
The following is the sample code for subscribing to the data changes of a single KV store:
```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log("dataChange callback call data: ${data}");
});
try{
kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log(`dataChange callback call data: ${data}`);
});
}catch(e){
console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`);
}
```
6. Write data to the single KV store.
......@@ -188,15 +190,15 @@ The following uses a single KV store as an example to describe the development p
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) {
console.log('Failed to put data: ${error}');
console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return;
}
console.log('Put data successfully');
});
} catch (e) {
console.log('An unexpected error occurred. Error: ${e}');
}catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```
......@@ -211,18 +213,22 @@ The following uses a single KV store as an example to describe the development p
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) {
console.log('Failed to put data: ${error}');
console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return;
}
console.log('Put data successfully');
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) {
console.log('Got data successfully: ${data}');
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) {
console.error(`Failed to get data.code is ${err.code},message is ${err.message}`);
return;
}
console.log(`Obtained data successfully:${data}`);
});
});
} catch (e) {
console.log('An unexpected error occurred. Error: ${e}');
}catch (e) {
console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
}
```
......@@ -233,7 +239,7 @@ The following uses a single KV store as an example to describe the development p
> **NOTE**<br>
>
> The APIs of the `deviceManager` module are system interfaces.
The following is the example code for synchronizing data in a single KV store:
```js
......@@ -254,9 +260,9 @@ The following uses a single KV store as an example to describe the development p
}
try{
// 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000);
kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) {
console.log('An unexpected error occurred. Error: ${e}');
console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`);
}
}
});
......
......@@ -18,7 +18,7 @@
- [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md)
- [@ohos.application.StartOptions](js-apis-application-StartOptions.md)
- [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md)
- [@ohos.application.WindowExtensionAbility](js-apis-application-WindowExtensionAbility.md)
- [@ohos.application.WindowExtensionAbility](js-apis-application-windowExtensionAbility.md)
- application/[AbilityContext](js-apis-ability-context.md)
- application/[ApplicationContext](js-apis-application-applicationContext.md)
- application/[AbilityStageContext](js-apis-abilitystagecontext.md)
......@@ -127,6 +127,7 @@
- [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md)
- [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md)
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md)
- [@ohos.data.preferences](js-apis-data-preferences.md)
- [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md)
......@@ -173,7 +174,7 @@
- Basic Features
- [@ohos.accessibility](js-apis-accessibility.md)
- [@ohos.accessibility.config](js-apis-accessibility-config.md)
- [@ohos.application.AccessibilityExtensionAbility](js-apis-application-AccessibilityExtensionAbility.md)
- [@ohos.application.AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md)
- [@ohos.faultLogger](js-apis-faultLogger.md)
- [@ohos.hichecker](js-apis-hichecker.md)
- [@ohos.hidebug](js-apis-hidebug.md)
......@@ -181,8 +182,8 @@
- [@ohos.hiSysEvent](js-apis-hisysevent.md)
- [@ohos.hiTraceChain](js-apis-hitracechain.md)
- [@ohos.hiTraceMeter](js-apis-hitracemeter.md)
- [@ohos.inputMethod](js-apis-inputmethod.md)
- [@ohos.inputMethodEngine](js-apis-inputmethodengine.md)
- [@ohos.inputmethod](js-apis-inputmethod.md)
- [@ohos.inputmethodengine](js-apis-inputmethodengine.md)
- [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md)
- [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md)
- [@ohos.pasteboard](js-apis-pasteboard.md)
......@@ -224,7 +225,7 @@
- [@ohos.account.osAccount](js-apis-osAccount.md)
- Custom Management
- [@ohos.configPolicy](js-apis-configPolicy.md)
- [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md)
- [@ohos.enterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md)
- Language Base Class Library
- [@ohos.buffer](js-apis-buffer.md)
- [@ohos.convertxml](js-apis-convertxml.md)
......
# Distributed KV Store Error Codes
## 15100001 Subscription Count Reaches the Limit
**Error Message**
Over max subscribe limits.
**Description**
The number of subscriptions has reached the limit for **on('dataChange')**.
**Possible Causes**
The number of subscriptions has reached the limit for **on('dataChange')**.
**Solution**
Unregister unnecessary subscriptions and try again.
## 15100002 Parameter Configuration Changes
**Error Message**
Open existed database with changed options.
**Description**
The **options** configuration changes when **getKVStore()** is called to obtain a KV store.
**Possible Causes**
The possible causes are as follows:
1. An existing **storeId** is used to create a KV store.
2. You want to change the **options** parameter of a KV store.
**Solution**
1. When creating a KV store, do not use a duplicate **storeId**.
2. Currently, the **options** parameter of a KV store cannot be changed. To apply the change, delete the KV store and create a KV store with the required **options** settings.
## 15100003 KV Store Corrupted
**Error Message**
Database corrupted.
**Description**
The target KV store is corrupted.
**Possible Causes**
The target KV store is corrupted.
**Solution**
1. Restore the KV store from a backup file.
2. If no backup file is available, delete the corrupted KV store and create a new one.
## 15100004 Failed to Find Data
**Error Message**
Not found.
**Description**
Related data is found when **deleteKVStore()**, **delete()**, **deleteBatch()**, or **get()** is called.
**Possible Causes**
The possible causes are as follows:
1. The KV store to delete does not exist or has been deleted.
2. The data queried does not exist or has been deleted.
3. The data to delete does not exist or has been deleted.
**Solution**
1. Before deleting a KV store, check that the KV store exists.
2. When querying data in a KV store, check whether the query keywords are correct.
3. When deleting data from a KV store, check that the keyword for the deletion is correct and the data to delete exists.
## 15100005 KV Store or Result Set Closed
**Error Message**
Database or result set already closed.
**Description**
The KV store or result set to operate is already closed.
**Possible Causes**
The KV store or result set is closed manually before the operation.
**Solution**
1. Obtain the KV store and try again.
2. Obtain the result set and try again.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册