File
Blob: src/workerd/api/sync-kv.h
| 1 | // Copyright (c) 2017-2025 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | #pragma once |
| 6 | |
| 7 | #include "actor-state.h" |
| 8 | |
| 9 | #include <workerd/jsg/jsg.h> |
| 10 | #include <workerd/jsg/iterator.h> |
| 11 | #include <workerd/util/sqlite-kv.h> |
| 12 | |
| 13 | namespace workerd::api { |
| 14 | |
| 15 | // Synchronous KV storage. Available as ctx.storage.kv on SQLite-backed DOs. |
| 16 | class SyncKvStorage: public jsg::Object { |
| 17 | public: |
| 18 | SyncKvStorage(jsg::Ref<DurableObjectStorage> storage): storage(kj::mv(storage)) {} |
| 19 | |
| 20 | struct ListOptions { |
| 21 | jsg::Optional<kj::String> start; |
| 22 | jsg::Optional<kj::String> startAfter; |
| 23 | jsg::Optional<kj::String> end; |
| 24 | jsg::Optional<kj::String> prefix; |
| 25 | jsg::Optional<bool> reverse; |
| 26 | jsg::Optional<int> limit; |
| 27 | |
| 28 | JSG_STRUCT(start, startAfter, end, prefix, reverse, limit); |
| 29 | JSG_STRUCT_TS_OVERRIDE(SyncKvListOptions); // Rename from SyncKvStorageListOptions |
| 30 | }; |
| 31 | |
| 32 | jsg::JsValue get(jsg::Lock& js, kj::String key); |
| 33 | |
| 34 | JSG_ITERATOR_TYPE(ListIterator, jsg::JsArray, IoOwn<SqliteKv::ListCursor>, listNext); |
| 35 | |
| 36 | jsg::Ref<ListIterator> list(jsg::Lock& js, jsg::Optional<ListOptions> options); |
| 37 | |
| 38 | void put(jsg::Lock& js, kj::String key, jsg::JsValue value); |
| 39 | |
| 40 | kj::OneOf<bool, int> delete_(jsg::Lock& js, kj::String key); |
| 41 | |
| 42 | JSG_RESOURCE_TYPE(SyncKvStorage) { |
| 43 | JSG_METHOD(get); |
| 44 | JSG_METHOD(list); |
| 45 | JSG_METHOD(put); |
| 46 | JSG_METHOD_NAMED(delete, delete_); |
| 47 | |
| 48 | JSG_TS_OVERRIDE({ |
| 49 | get<T = unknown>(key: string): T | undefined; |
| 50 | |
| 51 | list<T = unknown>(options?: SyncKvStorageListOptions): Iterable<[string, T]>; |
| 52 | |
| 53 | put<T>(key: string, value: T): void; |
| 54 | |
| 55 | delete(key: string): boolean; |
| 56 | }); |
| 57 | } |
| 58 | |
| 59 | private: |
| 60 | jsg::Ref<DurableObjectStorage> storage; |
| 61 | |
| 62 | SqliteKv& getSqliteKv(jsg::Lock& js) { |
| 63 | return storage->getSqliteKv(js); |
| 64 | } |
| 65 | |
| 66 | static kj::Maybe<jsg::JsArray> listNext(jsg::Lock& js, IoOwn<SqliteKv::ListCursor>& state); |
| 67 | }; |
| 68 | |
| 69 | #define EW_SYNC_KV_ISOLATE_TYPES api::SyncKvStorage, api::SyncKvStorage::ListOptions, \ |
| 70 | api::SyncKvStorage::ListIterator, api::SyncKvStorage::ListIterator::Next |
| 71 | |
| 72 | } // namespace workerd::api |