Skip to content

Commit

Permalink
Add null check to Json.Get<T> (#199)
Browse files Browse the repository at this point in the history
add null check to Json.Get<T>
  • Loading branch information
shacharPash authored Oct 25, 2023
1 parent e32b6b6 commit 954992e
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/NRedisStack/Json/JsonCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public RedisResult Get(RedisKey key, string[] paths, RedisValue? indent = null,
public T? Get<T>(RedisKey key, string path = "$", JsonSerializerOptions? serializerOptions = default)
{
var res = _db.Execute(JsonCommandBuilder.Get<T>(key, path));
if (res.Type == ResultType.BulkString)
if (res.Type == ResultType.BulkString && !res.IsNull)
{
var arr = JsonSerializer.Deserialize<JsonArray>(res.ToString()!);
if (arr?.Count > 0)
Expand Down
2 changes: 1 addition & 1 deletion src/NRedisStack/Json/JsonCommandsAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public async Task<RedisResult> GetAsync(RedisKey key, string[] paths, RedisValue
public async Task<T?> GetAsync<T>(RedisKey key, string path = "$", JsonSerializerOptions? serializerOptions = default)
{
var res = await _db.ExecuteAsync(JsonCommandBuilder.Get<T>(key, path));
if (res.Type == ResultType.BulkString)
if (res.Type == ResultType.BulkString && !res.IsNull)
{
var arr = JsonSerializer.Deserialize<JsonArray>(res.ToString()!);
if (arr?.Count > 0)
Expand Down
34 changes: 34 additions & 0 deletions tests/NRedisStack.Tests/Json/JsonTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1118,4 +1118,38 @@ public void TestJsonCommandBuilder()
}
Assert.Equal("JSON.GET", getBuild2.Command);
}

[Fact]
public void TestGetIssue198()
{
var commands = new JsonCommands(redisFixture.Redis.GetDatabase());
var keys = CreateKeyNames(1);
var key = keys[0];
commands.Set(key, "$", new Person() { Age = 35, Name = "Alice" });

// Path not found:
var result = commands.Get<Person>(key, "$.a"); // returns "[]" because the path is not found (but the key is)
// Key not found:
var result2 = commands.Get<Person>("notExistKey", "$.a"); // returns (nil) because the key is not found

Assert.Null(result);
Assert.Null(result2);
}

[Fact]
public async Task TestGetIssue198_Async()
{
var commands = new JsonCommandsAsync(redisFixture.Redis.GetDatabase());
var keys = CreateKeyNames(1);
var key = keys[0];
await commands.SetAsync(key, "$", new Person() { Age = 35, Name = "Alice" });

// Path not found:
var result = await commands.GetAsync<Person>(key, "$.a"); // returns "[]" because the path is not found (but the key is)
// Key not found:
var result2 = await commands.GetAsync<Person>("notExistKey", "$.a"); // returns (nil) because the key is not found

Assert.Null(result);
Assert.Null(result2);
}
}

0 comments on commit 954992e

Please sign in to comment.