1# Distributed Data Service Development 2 3## When to Use 4 5The Distributed Data Service (DDS) implements synchronization of application data across user devices. When data is added, deleted, or modified for an application on a device, the same application on another device can obtain the updated data. The DDS applies to the distributed gallery, messages, contacts, and file manager. 6 7 8## Available APIs 9 10For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md). 11 12 13**Table 1** APIs provided by the DDS 14 15| API | Description | 16| ------------------------------------------------------------ | ----------------------------------------------- | 17| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void<br>createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KVManager** object for database management.| 18| getKVStore<TextendsKVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void<br>getKVStore<TextendsKVStore>(storeId: string, options: Options): Promise<T> | Obtains a KV store with the specified **Options** and **storeId**.| 19| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | Inserts and updates data. | 20| delete(key: string, callback: AsyncCallback<void>): void<br>delete(key: string): Promise<void> | Deletes data. | 21| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void<br>get(key: string): Promise<Uint8Array\|string\|boolean\|number> | Queries data. | 22| on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void<br>on(event: 'syncComplete', syncCallback: Callback<Array<[string,number]>>): void | Subscribes to data changes in the KV store. | 23| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | 24 25 26 27 28## How to Develop 29 30The following uses a single KV store as an example to describe the development procedure. 31 321. Import the distributed data module. 33 34 ```js 35 import distributedData from '@ohos.data.distributedData'; 36 ``` 372. Apply for the required permission if data synchronization is required. 38 39 You need to configure the request permission in the **config.json** file. The sample code is as follows: 40 41 ```json 42 { 43 "module": { 44 "reqPermissions": [ 45 { 46 "name": "ohos.permission.DISTRIBUTED_DATASYNC" 47 } 48 ] 49 } 50 } 51 ``` 52 This permission must also be granted by the user when the application is started for the first time. The sample code is as follows: 53 54 ```js 55 import featureAbility from '@ohos.ability.featureAbility'; 56 57 function grantPermission() { 58 console.info('grantPermission'); 59 let context = featureAbility.getContext(); 60 context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { 61 console.info(`result.requestCode=${result.requestCode}`) 62 63 }) 64 console.info('end grantPermission'); 65 } 66 67 grantPermission(); 68 ``` 69 703. Create a **KvManager** instance based on the specified **KvManagerConfig** object. 71 72 1. Create a **kvManagerConfig** object based on the application context. 73 2. Create a **kvManager** instance. 74 75 The sample code is as follows: 76 ```js 77 let kvManager; 78 try { 79 const kvManagerConfig = { 80 bundleName : 'com.example.datamanagertest', 81 userInfo : { 82 userId : '0', 83 userType : distributedData.UserType.SAME_USER_ID 84 } 85 } 86 distributedData.createKVManager(kvManagerConfig, function (err, manager) { 87 if (err) { 88 console.log("createKVManager err: " + JSON.stringify(err)); 89 return; 90 } 91 console.log("createKVManager success"); 92 kvManager = manager; 93 }); 94 } catch (e) { 95 console.log("An unexpected error occurred. Error:" + e); 96 } 97 ``` 98 994. Create and obtain a single KV store. 100 101 1. Declare the ID of the single KV store to create. 102 2. Create a single KV store. You are advised to disable automatic synchronization (`autoSync:false`) and call `sync` when a synchronization is required. 103 104 The sample code is as follows: 105 ```js 106 let kvStore; 107 try { 108 const options = { 109 createIfMissing : true, 110 encrypt : false, 111 backup : false, 112 autoSync : false, 113 kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, 114 securityLevel : distributedData.SecurityLevel.S0, 115 }; 116 kvManager.getKVStore('storeId', options, function (err, store) { 117 if (err) { 118 console.log("getKVStore err: " + JSON.stringify(err)); 119 return; 120 } 121 console.log("getKVStore success"); 122 kvStore = store; 123 }); 124 } catch (e) { 125 console.log("An unexpected error occurred. Error:" + e); 126 } 127 ``` 128 129 > **NOTE** 130 > 131 > 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. 132 1335. Subscribe to changes in the distributed data. 134 135 The following is the sample code for subscribing to the data changes of a single KV store: 136 ```js 137 kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { 138 console.log("dataChange callback call data: " + JSON.stringify(data)); 139 }); 140 ``` 141 1426. Write data to the single KV store. 143 144 1. Construct the `Key` and `Value` to be written into the single KV store. 145 2. Write key-value pairs into the single KV store. 146 147 The following is the sample code for writing key-value pairs of the string type into the single KV store: 148 149 ```js 150 const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 151 const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 152 try { 153 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { 154 if (err != undefined) { 155 console.log("put err: " + JSON.stringify(err)); 156 return; 157 } 158 console.log("put success"); 159 }); 160 }catch (e) { 161 console.log("An unexpected error occurred. Error:" + e); 162 } 163 ``` 164 1657. Query data in the single KV store. 166 167 1. Construct the `Key` to be queried from the single KV store. 168 2. Query data from the single KV store. 169 170 The following is the sample code for querying data of the string type from the single KV store: 171 ```js 172 const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 173 const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 174 try { 175 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { 176 if (err != undefined) { 177 console.log("put err: " + JSON.stringify(err)); 178 return; 179 } 180 console.log("put success"); 181 kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { 182 console.log("get success data: " + data); 183 }); 184 }); 185 }catch (e) { 186 console.log("An unexpected error occurred. Error:" + e); 187 } 188 ``` 189 1908. Synchronize data to other devices. 191 192 Select the devices in the same network and the synchronization mode to synchronize data. 193 194 > **NOTE** 195 > 196 > The APIs of the `deviceManager` module are system interfaces. 197 198 The following is the sample code for synchronizing data in a single KV store: 199 ```js 200 import deviceManager from '@ohos.distributedHardware.deviceManager'; 201 202 let devManager; 203 // Create deviceManager. 204 deviceManager.createDeviceManager("bundleName", (err, value) => { 205 if (!err) { 206 devManager = value; 207 // deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync(). 208 let deviceIds = []; 209 if (devManager != null) { 210 var devices = devManager.getTrustedDeviceListSync(); 211 for (var i = 0; i < devices.length; i++) { 212 deviceIds[i] = devices[i].deviceId; 213 } 214 } 215 try{ 216 // 1000 indicates that the maximum delay is 1000 ms. 217 kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); 218 }catch (e) { 219 console.log("An unexpected error occurred. Error:" + e); 220 } 221 } 222 }); 223 ``` 224