Fix js get and close store

pull/1860/head
Tony 8 months ago
parent 718f5dc90d
commit 4f13a03401
No known key found for this signature in database
GPG Key ID: 34BDD3EA27824956

@ -79,10 +79,6 @@
], ],
"deny": ["$APPDATA/db/*.stronghold"] "deny": ["$APPDATA/db/*.stronghold"]
}, },
"store:allow-entries", "store:default"
"store:allow-get",
"store:allow-set",
"store:allow-save",
"store:allow-load"
] ]
} }

@ -67,7 +67,8 @@ pub fn run() {
.user_agent(&format!("Tauri API - {}", std::env::consts::OS)) .user_agent(&format!("Tauri API - {}", std::env::consts::OS))
.title("Tauri API Validation") .title("Tauri API Validation")
.inner_size(1000., 800.) .inner_size(1000., 800.)
.min_inner_size(600., 400.); .min_inner_size(600., 400.)
.visible(false);
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]

@ -7,15 +7,23 @@
let key; let key;
let value; let value;
const store = new LazyStore("cache.json"); let store = new LazyStore("cache.json");
let cache = {}; let cache = {};
onMount(async () => { async function refreshEntries() {
try {
const values = await store.entries(); const values = await store.entries();
cache = {};
for (const [key, value] of values) { for (const [key, value] of values) {
cache[key] = value; cache[key] = value;
} }
cache = cache; } catch (error) {
onMessage(error);
}
}
onMount(async () => {
await refreshEntries();
}); });
async function write(key, value) { async function write(key, value) {
@ -23,11 +31,33 @@
await store.set(key, value); await store.set(key, value);
const v = await store.get(key); const v = await store.get(key);
cache[key] = v; cache[key] = v;
cache = cache;
} catch (error) { } catch (error) {
onMessage(error); onMessage(error);
} }
} }
async function reset() {
try {
await store.reset();
} catch (error) {
onMessage(error);
}
await refreshEntries();
}
async function close() {
try {
await store.close();
onMessage("Store is now closed, any new operations will now errors out");
} catch (error) {
onMessage(error);
}
}
function reopen() {
store = new LazyStore("cache.json");
onMessage("We made a new `LazyStore` instance, operations will now work");
}
</script> </script>
<div class="flex flex-col childre:grow gap-1"> <div class="flex flex-col childre:grow gap-1">
@ -42,7 +72,12 @@
<input class="grow input" bind:value /> <input class="grow input" bind:value />
</div> </div>
<div>
<button class="btn" on:click={() => write(key, value)}>Write</button> <button class="btn" on:click={() => write(key, value)}>Write</button>
<button class="btn" on:click={() => reset()}>Reset</button>
<button class="btn" on:click={() => close()}>Close</button>
<button class="btn" on:click={() => reopen()}>Re-open</button>
</div>
</div> </div>
<div> <div>

@ -1 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_STORE__=function(t){"use strict";var e,r;function a(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}async function s(t,e={},r){return window.__TAURI_INTERNALS__.invoke(t,e,r)}"function"==typeof SuppressedError&&SuppressedError;class i{get rid(){return function(t,e,r,a){if("a"===r&&!a)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!a:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(t):a?a.value:e.get(t)}(this,e,"f")}constructor(t){e.set(this,void 0),function(t,e,r,a,s){if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");e.set(t,r)}(this,e,t)}async close(){return s("plugin:resources|close",{rid:this.rid})}}async function n(t,e,r){const i={kind:"Any"};return s("plugin:event|listen",{event:t,target:i,handler:a(e)}).then((e=>async()=>async function(t,e){await s("plugin:event|unlisten",{event:t,eventId:e})}(t,e)))}async function o(t,e){return await u.createStore(t,e)}async function c(t){return await u.getStore(t)}e=new WeakMap,function(t){t.WINDOW_RESIZED="tauri://resize",t.WINDOW_MOVED="tauri://move",t.WINDOW_CLOSE_REQUESTED="tauri://close-requested",t.WINDOW_DESTROYED="tauri://destroyed",t.WINDOW_FOCUS="tauri://focus",t.WINDOW_BLUR="tauri://blur",t.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",t.WINDOW_THEME_CHANGED="tauri://theme-changed",t.WINDOW_CREATED="tauri://window-created",t.WEBVIEW_CREATED="tauri://webview-created",t.DRAG_ENTER="tauri://drag-enter",t.DRAG_OVER="tauri://drag-over",t.DRAG_DROP="tauri://drag-drop",t.DRAG_LEAVE="tauri://drag-leave"}(r||(r={}));class u extends i{constructor(t){super(t)}static async createStore(t,e){const r=await s("plugin:store|create_store",{path:t,...e});return new u(r)}static async getStore(t){const e=await s("plugin:store|get_store",{path:t});return e?new u(e):void 0}async set(t,e){await s("plugin:store|set",{rid:this.rid,key:t,value:e})}async get(t){return await s("plugin:store|get",{rid:this.rid,key:t})}async has(t){return await s("plugin:store|has",{rid:this.rid,key:t})}async delete(t){return await s("plugin:store|delete",{rid:this.rid,key:t})}async clear(){await s("plugin:store|clear",{rid:this.rid})}async reset(){await s("plugin:store|reset",{rid:this.rid})}async keys(){return await s("plugin:store|keys",{rid:this.rid})}async values(){return await s("plugin:store|values",{rid:this.rid})}async entries(){return await s("plugin:store|entries",{rid:this.rid})}async length(){return await s("plugin:store|length",{rid:this.rid})}async load(){await s("plugin:store|load",{rid:this.rid})}async save(){await s("plugin:store|save",{rid:this.rid})}async onKeyChange(t,e){return await n("store://change",(r=>{r.payload.resourceId===this.rid&&r.payload.key===t&&e(r.payload.value)}))}async onChange(t){return await n("store://change",(e=>{e.payload.resourceId===this.rid&&t(e.payload.key,e.payload.value)}))}}return t.LazyStore=class{get store(){return this._store||(this._store=c(this.path).then((async t=>t||await o(this.path,this.options)))),this._store}constructor(t,e){this.path=t,this.options=e}async init(){await this.store}async set(t,e){return(await this.store).set(t,e)}async get(t){return(await this.store).get(t)}async has(t){return(await this.store).has(t)}async delete(t){return(await this.store).delete(t)}async clear(){await(await this.store).clear()}async reset(){await(await this.store).reset()}async keys(){return(await this.store).keys()}async values(){return(await this.store).values()}async entries(){return(await this.store).entries()}async length(){return(await this.store).length()}async load(){await(await this.store).load()}async save(){await(await this.store).save()}async onKeyChange(t,e){return(await this.store).onKeyChange(t,e)}async onChange(t){return(await this.store).onChange(t)}async close(){this._store&&await(await this._store).close()}},t.Store=u,t.createStore=o,t.getStore=c,t}({});Object.defineProperty(window.__TAURI__,"store",{value:__TAURI_PLUGIN_STORE__})} if("__TAURI__"in window){var __TAURI_PLUGIN_STORE__=function(t){"use strict";var e,r;function a(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}async function s(t,e={},r){return window.__TAURI_INTERNALS__.invoke(t,e,r)}"function"==typeof SuppressedError&&SuppressedError;class i{get rid(){return function(t,e,r,a){if("a"===r&&!a)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!a:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(t):a?a.value:e.get(t)}(this,e,"f")}constructor(t){e.set(this,void 0),function(t,e,r,a,s){if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");e.set(t,r)}(this,e,t)}async close(){return s("plugin:resources|close",{rid:this.rid})}}async function n(t,e,r){const i={kind:"Any"};return s("plugin:event|listen",{event:t,target:i,handler:a(e)}).then((e=>async()=>async function(t,e){await s("plugin:event|unlisten",{event:t,eventId:e})}(t,e)))}async function o(t,e){return await u.createStore(t,e)}async function c(t){return await u.getStore(t)}e=new WeakMap,function(t){t.WINDOW_RESIZED="tauri://resize",t.WINDOW_MOVED="tauri://move",t.WINDOW_CLOSE_REQUESTED="tauri://close-requested",t.WINDOW_DESTROYED="tauri://destroyed",t.WINDOW_FOCUS="tauri://focus",t.WINDOW_BLUR="tauri://blur",t.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",t.WINDOW_THEME_CHANGED="tauri://theme-changed",t.WINDOW_CREATED="tauri://window-created",t.WEBVIEW_CREATED="tauri://webview-created",t.DRAG_ENTER="tauri://drag-enter",t.DRAG_OVER="tauri://drag-over",t.DRAG_DROP="tauri://drag-drop",t.DRAG_LEAVE="tauri://drag-leave"}(r||(r={}));class u extends i{constructor(t){super(t)}static async createStore(t,e){const r=await s("plugin:store|create_store",{path:t,...e});return new u(r)}static async getStore(t){const e=await s("plugin:store|get_store",{path:t});return e?new u(e):void 0}async set(t,e){await s("plugin:store|set",{rid:this.rid,key:t,value:e})}async get(t){return await s("plugin:store|get",{rid:this.rid,key:t})}async has(t){return await s("plugin:store|has",{rid:this.rid,key:t})}async delete(t){return await s("plugin:store|delete",{rid:this.rid,key:t})}async clear(){await s("plugin:store|clear",{rid:this.rid})}async reset(){await s("plugin:store|reset",{rid:this.rid})}async keys(){return await s("plugin:store|keys",{rid:this.rid})}async values(){return await s("plugin:store|values",{rid:this.rid})}async entries(){return await s("plugin:store|entries",{rid:this.rid})}async length(){return await s("plugin:store|length",{rid:this.rid})}async load(){await s("plugin:store|load",{rid:this.rid})}async save(){await s("plugin:store|save",{rid:this.rid})}async onKeyChange(t,e){return await n("store://change",(r=>{r.payload.resourceId===this.rid&&r.payload.key===t&&e(r.payload.value)}))}async onChange(t){return await n("store://change",(e=>{e.payload.resourceId===this.rid&&t(e.payload.key,e.payload.value)}))}async close(){await s("plugin:store|close_store",{rid:this.rid})}}return t.LazyStore=class{get store(){return this._store||(this._store=c(this.path).then((async t=>t||await o(this.path,this.options)))),this._store}constructor(t,e){this.path=t,this.options=e}async init(){await this.store}async set(t,e){return(await this.store).set(t,e)}async get(t){return(await this.store).get(t)}async has(t){return(await this.store).has(t)}async delete(t){return(await this.store).delete(t)}async clear(){await(await this.store).clear()}async reset(){await(await this.store).reset()}async keys(){return(await this.store).keys()}async values(){return(await this.store).values()}async entries(){return(await this.store).entries()}async length(){return(await this.store).length()}async load(){await(await this.store).load()}async save(){await(await this.store).save()}async onKeyChange(t,e){return(await this.store).onKeyChange(t,e)}async onChange(t){return(await this.store).onChange(t)}async close(){this._store&&await(await this._store).close()}},t.Store=u,t.createStore=o,t.getStore=c,t}({});Object.defineProperty(window.__TAURI__,"store",{value:__TAURI_PLUGIN_STORE__})}

@ -5,6 +5,7 @@
const COMMANDS: &[&str] = &[ const COMMANDS: &[&str] = &[
"create_store", "create_store",
"get_store", "get_store",
"close_store",
"set", "set",
"get", "get",
"has", "has",

@ -276,6 +276,11 @@ export class Store extends Resource implements IStore {
} }
}) })
} }
async close(): Promise<void> {
// The default close on `Resource` can only close resources in the webview's resource table
await invoke('plugin:store|close_store', { rid: this.rid })
}
} }
interface IStore { interface IStore {

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-close"
description = "Enables the close command without any pre-configured scope."
commands.allow = ["close"]
[[permission]]
identifier = "deny-close"
description = "Denies the close command without any pre-configured scope."
commands.deny = ["close"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-close-store"
description = "Enables the close_store command without any pre-configured scope."
commands.allow = ["close_store"]
[[permission]]
identifier = "deny-close-store"
description = "Denies the close_store command without any pre-configured scope."
commands.deny = ["close_store"]

@ -11,6 +11,7 @@ All operations are enabled by default.
- `allow-create-store` - `allow-create-store`
- `allow-get-store` - `allow-get-store`
- `allow-close-store`
- `allow-clear` - `allow-clear`
- `allow-delete` - `allow-delete`
- `allow-entries` - `allow-entries`
@ -62,6 +63,58 @@ Denies the clear command without any pre-configured scope.
<tr> <tr>
<td> <td>
`store:allow-close`
</td>
<td>
Enables the close command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-close`
</td>
<td>
Denies the close command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-close-store`
</td>
<td>
Enables the close_store command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-close-store`
</td>
<td>
Denies the close_store command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-create-store` `store:allow-create-store`
</td> </td>

@ -13,6 +13,7 @@ All operations are enabled by default.
permissions = [ permissions = [
"allow-create-store", "allow-create-store",
"allow-get-store", "allow-get-store",
"allow-close-store",
"allow-clear", "allow-clear",
"allow-delete", "allow-delete",
"allow-entries", "allow-entries",

@ -304,6 +304,26 @@
"type": "string", "type": "string",
"const": "deny-clear" "const": "deny-clear"
}, },
{
"description": "Enables the close command without any pre-configured scope.",
"type": "string",
"const": "allow-close"
},
{
"description": "Denies the close command without any pre-configured scope.",
"type": "string",
"const": "deny-close"
},
{
"description": "Enables the close_store command without any pre-configured scope.",
"type": "string",
"const": "allow-close-store"
},
{
"description": "Denies the close_store command without any pre-configured scope.",
"type": "string",
"const": "deny-close-store"
},
{ {
"description": "Enables the create_store command without any pre-configured scope.", "description": "Enables the create_store command without any pre-configured scope.",
"type": "string", "type": "string",

@ -21,6 +21,7 @@ use std::{
sync::{Arc, Mutex}, sync::{Arc, Mutex},
time::Duration, time::Duration,
}; };
use store::resolve_store_path;
pub use store::{DeserializeFn, SerializeFn, Store, StoreBuilder, StoreInner}; pub use store::{DeserializeFn, SerializeFn, Store, StoreBuilder, StoreInner};
use tauri::{ use tauri::{
plugin::{self, TauriPlugin}, plugin::{self, TauriPlugin},
@ -96,12 +97,18 @@ async fn create_store<R: Runtime>(
} }
#[tauri::command] #[tauri::command]
async fn get_store( async fn get_store<R: Runtime>(
app: AppHandle<R>,
store_collection: State<'_, StoreCollection>, store_collection: State<'_, StoreCollection>,
path: PathBuf, path: PathBuf,
) -> Result<Option<ResourceId>> { ) -> Result<Option<ResourceId>> {
let stores = store_collection.stores.lock().unwrap(); let stores = store_collection.stores.lock().unwrap();
Ok(stores.get(&path).copied()) Ok(stores.get(&resolve_store_path(app, path)).copied())
}
#[tauri::command]
async fn close_store<R: Runtime>(app: AppHandle<R>, rid: ResourceId) -> Result<()> {
Ok(app.resources_table().close(rid)?)
} }
#[tauri::command] #[tauri::command]
@ -275,6 +282,7 @@ impl<R: Runtime> Builder<R> {
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
create_store, create_store,
get_store, get_store,
close_store,
set, set,
get, get,
has, has,
@ -286,7 +294,7 @@ impl<R: Runtime> Builder<R> {
length, length,
entries, entries,
load, load,
save save,
]) ])
.setup(move |app_handle, _api| { .setup(move |app_handle, _api| {
app_handle.manage(StoreCollection { app_handle.manage(StoreCollection {

@ -36,6 +36,12 @@ fn default_deserialize(
serde_json::from_slice(bytes).map_err(Into::into) serde_json::from_slice(bytes).map_err(Into::into)
} }
pub(crate) fn resolve_store_path<R: Runtime>(app: AppHandle<R>, path: impl AsRef<Path>) -> PathBuf {
app.path()
.resolve(path, BaseDirectory::AppData)
.expect("failed to resolve app dir")
}
/// Builds a [`Store`] /// Builds a [`Store`]
pub struct StoreBuilder<R: Runtime> { pub struct StoreBuilder<R: Runtime> {
app: AppHandle<R>, app: AppHandle<R>,
@ -60,10 +66,7 @@ impl<R: Runtime> StoreBuilder<R> {
/// ``` /// ```
pub fn new<M: Manager<R>, P: AsRef<Path>>(manager: &M, path: P) -> Self { pub fn new<M: Manager<R>, P: AsRef<Path>>(manager: &M, path: P) -> Self {
let app = manager.app_handle().clone(); let app = manager.app_handle().clone();
let path = app let path = resolve_store_path(app.clone(), path);
.path()
.resolve(path, BaseDirectory::AppData)
.expect("failed to resolve app dir");
Self { Self {
app, app,
// Since Store.path is only exposed to the user in emit calls we may as well simplify it here already. // Since Store.path is only exposed to the user in emit calls we may as well simplify it here already.

Loading…
Cancel
Save