Skip to content

Commit 9bca982

Browse files
committed
feat: allows store items to be read as JSON.
1 parent d0195d8 commit 9bca982

File tree

4 files changed

+19
-0
lines changed

4 files changed

+19
-0
lines changed

docs/stores.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,15 @@ if (exampleStore.hasItemWithKey('example')) {
5252
}
5353
```
5454

55+
Read a store item as JSON:
56+
57+
```js
58+
var json = exampleStore.loadAsJson('foo');
59+
60+
// prints the 'foo' item as JSON
61+
console.log(json);
62+
```
63+
5564
## The Stores REST API
5665

5766
You can also retrieve or save data to a store through the `/system/store` API. This can be useful for tests to verify what was sent to a mock:

store/common/src/main/java/io/gatehill/imposter/store/core/AbstractStore.kt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ package io.gatehill.imposter.store.core
4444

4545
import io.gatehill.imposter.http.ExchangePhase
4646
import io.gatehill.imposter.service.DeferredOperationService
47+
import io.gatehill.imposter.util.MapUtil
4748
import org.apache.logging.log4j.LogManager
4849
import org.apache.logging.log4j.Logger
4950

@@ -55,6 +56,10 @@ abstract class AbstractStore(
5556
) : Store {
5657
private val logger: Logger = LogManager.getLogger(AbstractStore::class.java)
5758

59+
override fun loadAsJson(key: String): String {
60+
return MapUtil.jsonify(load(key))
61+
}
62+
5863
override fun save(key: String, value: Any?, phase: ExchangePhase) {
5964
if (phase == ExchangePhase.RESPONSE_SENT && isEphemeral) {
6065
throw IllegalStateException("Cannot use deferred persistence for ephemeral store: $storeName of type: $typeDescription")

store/common/src/main/java/io/gatehill/imposter/store/core/PrefixedKeyStore.kt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,10 @@ class PrefixedKeyStore(
7373

7474
override fun <T> load(key: String): T? = delegate.load(buildKey(key))
7575

76+
override fun loadAsJson(key: String): String {
77+
return delegate.loadAsJson(buildKey(key))
78+
}
79+
7680
override fun loadByKeyPrefix(keyPrefix: String): Map<String, Any?> = delegate.loadByKeyPrefix(keyPrefix)
7781

7882
override fun delete(key: String) {

store/common/src/main/java/io/gatehill/imposter/store/core/Store.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ interface Store {
5858
phase: ExchangePhase = ExchangePhase.REQUEST_RECEIVED,
5959
)
6060
fun <T> load(key: String): T?
61+
fun loadAsJson(key: String): String
6162
fun delete(key: String)
6263
fun loadAll(): Map<String, Any?>
6364
fun loadByKeyPrefix(keyPrefix: String): Map<String, Any?>

0 commit comments

Comments
 (0)