Skip to content

Commit ff9bddd

Browse files
committed
make api consistent with the JS implementation, add examples
1 parent 083c165 commit ff9bddd

File tree

4 files changed

+159
-63
lines changed

4 files changed

+159
-63
lines changed

plugins/store/api-iife.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

plugins/store/guest-js/index.ts

Lines changed: 53 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -38,31 +38,31 @@ export type StoreOptions = {
3838
*
3939
* @throws If a store at that path already exists
4040
*/
41-
export async function createStore(
41+
export async function create(
4242
path: string,
4343
options?: StoreOptions
4444
): Promise<Store> {
45-
return await Store.createStore(path, options)
45+
return await Store.create(path, options)
4646
}
4747

4848
/**
49-
* Create a new Store or get the existing store with the path
49+
* Create a new Store or load the existing store with the path
5050
*
5151
* @param path Path to save the store in `app_data_dir`
5252
* @param options Store configuration options
5353
*/
54-
export async function createOrExistingStore(
54+
export async function createOrLoad(
5555
path: string,
5656
options?: StoreOptions
5757
): Promise<Store> {
58-
return await Store.createOrExistingStore(path, options)
58+
return await Store.createOrLoad(path, options)
5959
}
6060

6161
/**
62-
* @param path Path of the store in the rust side
62+
* @param path Path of the store
6363
*/
64-
export async function getStore(path: string): Promise<Store | undefined> {
65-
return await Store.getStore(path)
64+
export async function getStore(path: string): Promise<Store | null> {
65+
return await Store.get(path)
6666
}
6767

6868
/**
@@ -73,7 +73,7 @@ export class LazyStore implements IStore {
7373

7474
private get store(): Promise<Store> {
7575
if (!this._store) {
76-
this._store = createOrExistingStore(this.path, this.options)
76+
this._store = createOrLoad(this.path, this.options)
7777
}
7878
return this._store
7979
}
@@ -172,15 +172,24 @@ export class Store extends Resource implements IStore {
172172
}
173173

174174
/**
175+
* Create a new store.
176+
*
177+
* If the store already exists, its data will be overwritten.
178+
*
179+
* If the store is already loaded you must use {@link getStore} instead.
180+
*
181+
* @example
182+
* ```typescript
183+
* import { Store } from '@tauri-apps/api/store';
184+
* const store = await Store.create('store.json');
185+
* ```
186+
*
175187
* @param path Path to save the store in `app_data_dir`
176188
* @param options Store configuration options
177189
*
178190
* @throws If a store at that path already exists
179191
*/
180-
static async createStore(
181-
path: string,
182-
options?: StoreOptions
183-
): Promise<Store> {
192+
static async create(path: string, options?: StoreOptions): Promise<Store> {
184193
const rid = await invoke<number>('plugin:store|create_store', {
185194
path,
186195
...options
@@ -189,7 +198,18 @@ export class Store extends Resource implements IStore {
189198
}
190199

191200
/**
192-
* Create a new Store or get the existing store with the path
201+
* Create a new Store or load the existing store with the path.
202+
*
203+
* If the store is already loaded you must use {@link getStore} instead.
204+
*
205+
* @example
206+
* ```typescript
207+
* import { Store } from '@tauri-apps/api/store';
208+
* let store = await Store.get('store.json');
209+
* if (!store) {
210+
* store = await Store.createOrLoad('store.json');
211+
* }
212+
* ```
193213
*
194214
* @param path Path to save the store in `app_data_dir`
195215
* @param options Store configuration options
@@ -206,11 +226,26 @@ export class Store extends Resource implements IStore {
206226
}
207227

208228
/**
209-
* @param path Path of the store in the rust side
229+
* Gets an already loaded store.
230+
*
231+
* If the store is not loaded, returns `null`. In this case,
232+
* you must either {@link Store.create | create} it or {@link Store.createOrLoad createOrLoad} it.
233+
*
234+
* @example
235+
* ```typescript
236+
* import { Store } from '@tauri-apps/api/store';
237+
* let store = await Store.get('store.json');
238+
* if (!store) {
239+
* store = await Store.createOrLoad('store.json');
240+
* }
241+
* ```
242+
*
243+
* @param path Path of the store.
210244
*/
211-
static async getStore(path: string): Promise<Store | undefined> {
212-
const rid = await invoke<number | null>('plugin:store|get_store', { path })
213-
return rid ? new Store(rid) : undefined
245+
static async get(path: string): Promise<Store | null> {
246+
return await invoke<number | null>('plugin:store|get_store', { path }).then(
247+
(rid) => (rid ? new Store(rid) : null)
248+
)
214249
}
215250

216251
async set(key: string, value: unknown): Promise<void> {

plugins/store/src/lib.rs

Lines changed: 83 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ async fn create_store<R: Runtime>(
112112
serialize_fn_name,
113113
deserialize_fn_name,
114114
)?;
115-
let (_, rid) = builder.build_inner()?;
115+
let (_, rid) = builder.create_inner()?;
116116
Ok(rid)
117117
}
118118

@@ -133,7 +133,7 @@ async fn create_or_load<R: Runtime>(
133133
serialize_fn_name,
134134
deserialize_fn_name,
135135
)?;
136-
let (_, rid) = builder.build_or_existing_inner()?;
136+
let (_, rid) = builder.create_or_load_inner()?;
137137
Ok(rid)
138138
}
139139

@@ -242,23 +242,95 @@ async fn save<R: Runtime>(app: AppHandle<R>, rid: ResourceId) -> Result<()> {
242242
}
243243

244244
pub trait StoreExt<R: Runtime> {
245-
/// Create a store or get an existing store with default settings at path
245+
/// Create a store or load an existing store with default settings at the given path.
246+
///
247+
/// If the store is already loaded, its instance is automatically returned.
248+
///
249+
/// # Examples
250+
///
251+
/// ```
252+
/// use tauri_plugin_store::StoreExt;
253+
///
254+
/// tauri::Builder::default()
255+
/// .plugin(tauri_plugin_store::Builder::default().build())
256+
/// .setup(|app| {
257+
/// let store = app.store("my-store")?;
258+
/// Ok(())
259+
/// });
260+
/// ```
246261
fn store(&self, path: impl AsRef<Path>) -> Result<Arc<Store<R>>>;
247-
/// Create a store with default settings
262+
/// Create a store with default settings.
263+
///
264+
/// If the store is already loaded you must check with [`Self::get_store`] or prefer [`Self::store`]
265+
/// as it will return `Err(Error::AlreadyExists)`.
266+
///
267+
/// # Examples
268+
///
269+
/// ```
270+
/// use tauri_plugin_store::StoreExt;
271+
///
272+
/// tauri::Builder::default()
273+
/// .plugin(tauri_plugin_store::Builder::default().build())
274+
/// .setup(|app| {
275+
/// let store = app.create_store("my-store")?;
276+
/// Ok(())
277+
/// });
278+
/// ```
248279
fn create_store(&self, path: impl AsRef<Path>) -> Result<Arc<Store<R>>>;
249-
/// Get a store builder
280+
/// Get a store builder.
281+
///
282+
/// The builder can be used to configure the store.
283+
/// To use the default settings see [`Self::store`].
284+
///
285+
/// # Examples
286+
///
287+
/// ```
288+
/// use tauri_plugin_store::StoreExt;
289+
/// use std::time::Duration;
290+
///
291+
/// tauri::Builder::default()
292+
/// .plugin(tauri_plugin_store::Builder::default().build())
293+
/// .setup(|app| {
294+
/// let store = app.store_builder("users.json").auto_save(Duration::from_secs(1)).create_or_load()?;
295+
/// Ok(())
296+
/// });
297+
/// ```
250298
fn store_builder(&self, path: impl AsRef<Path>) -> StoreBuilder<R>;
251-
/// Get an existing store
299+
/// Get a handle of an already loaded store.
300+
///
301+
/// If the store is not loaded or does not exist, it returns `None`.
302+
/// In this case, you should initialize it with [`Self::store`].
303+
///
304+
/// # Examples
305+
///
306+
/// ```
307+
/// use tauri_plugin_store::StoreExt;
308+
///
309+
/// tauri::Builder::default()
310+
/// .plugin(tauri_plugin_store::Builder::default().build())
311+
/// .setup(|app| {
312+
/// let store = if let Some(s) = app.get_store("store.json") {
313+
/// s
314+
/// } else {
315+
/// app.store("store.json")?
316+
/// };
317+
/// Ok(())
318+
/// });
319+
/// ```
252320
fn get_store(&self, path: impl AsRef<Path>) -> Option<Arc<Store<R>>>;
253321
}
254322

255323
impl<R: Runtime, T: Manager<R>> StoreExt<R> for T {
256324
fn store(&self, path: impl AsRef<Path>) -> Result<Arc<Store<R>>> {
257-
StoreBuilder::new(self.app_handle(), path).build_or_existing()
325+
let path = path.as_ref();
326+
if let Some(store) = self.get_store(path) {
327+
return Ok(store);
328+
}
329+
StoreBuilder::new(self.app_handle(), path).create_or_load()
258330
}
259331

260332
fn create_store(&self, path: impl AsRef<Path>) -> Result<Arc<Store<R>>> {
261-
StoreBuilder::new(self.app_handle(), path).build()
333+
StoreBuilder::new(self.app_handle(), path).create()
262334
}
263335

264336
fn store_builder(&self, path: impl AsRef<Path>) -> StoreBuilder<R> {
@@ -327,7 +399,7 @@ impl<R: Runtime> Builder<R> {
327399
/// tauri_plugin_store::Builder::default()
328400
/// .register_serialize_fn("no-pretty-json".to_owned(), no_pretty_json)
329401
/// .build(),
330-
/// )
402+
/// );
331403
/// ```
332404
pub fn register_serialize_fn(mut self, name: String, serialize_fn: SerializeFn) -> Self {
333405
self.serialize_fns.insert(name, serialize_fn);
@@ -356,7 +428,7 @@ impl<R: Runtime> Builder<R> {
356428
/// tauri_plugin_store::Builder::default()
357429
/// .default_serialize_fn(no_pretty_json)
358430
/// .build(),
359-
/// )
431+
/// );
360432
/// ```
361433
pub fn default_serialize_fn(mut self, serialize_fn: SerializeFn) -> Self {
362434
self.default_serialize = serialize_fn;
@@ -377,7 +449,7 @@ impl<R: Runtime> Builder<R> {
377449
/// tauri::Builder::default()
378450
/// .plugin(tauri_plugin_store::Builder::default().build())
379451
/// .setup(|app| {
380-
/// let store = tauri_plugin_store::StoreBuilder::new(app, "store.bin").build()?;
452+
/// let store = tauri_plugin_store::StoreBuilder::new(app, "store.bin").create_or_load()?;
381453
/// Ok(())
382454
/// });
383455
/// ```

0 commit comments

Comments
 (0)