Skip to content
This repository was archived by the owner on Apr 20, 2020. It is now read-only.

Commit 4f9df61

Browse files
authored
Merge pull request #21 from RedisLabsModules/type
Add support for JSON.TYPE
2 parents 20fd867 + 0a72e7d commit 4f9df61

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/lib.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,21 @@ fn json_get(ctx: &Context, args: Vec<String>) -> RedisResult {
4747
Ok(value)
4848
}
4949

50+
fn json_type(ctx: &Context, args: Vec<String>) -> RedisResult {
51+
let mut args = args.into_iter().skip(1);
52+
let key = args.next_string()?;
53+
let path = args.next_string()?;
54+
55+
let key = ctx.open_key_writable(&key);
56+
57+
let value = match key.get_value::<RedisJSON>(&REDIS_JSON_TYPE)? {
58+
Some(doc) => { doc.get_type(&path)?.into() }
59+
None => ().into()
60+
};
61+
62+
Ok(value)
63+
}
64+
5065
//////////////////////////////////////////////////////
5166

5267
redis_module! {
@@ -58,5 +73,6 @@ redis_module! {
5873
commands: [
5974
["json.set", json_set, "write"],
6075
["json.get", json_get, ""],
76+
["json.type", json_type, ""],
6177
],
6278
}

src/redisjson.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,30 @@ impl RedisJSON {
6464

6565
return Ok(s)
6666
}
67+
68+
pub fn get_type(&self, path: &str) -> Result<String, Error> {
69+
let s = match self.get_doc(path)? {
70+
Some(doc) => {
71+
match doc {
72+
Value::Null => "null",
73+
Value::Bool(_) => "boolean",
74+
Value::Number(_) => "number",
75+
Value::String(_) => "string",
76+
Value::Array(_) => "array",
77+
Value::Object(_) => "object",
78+
}
79+
}
80+
None => ""
81+
};
82+
Ok(s.to_string())
83+
}
84+
85+
pub fn get_doc(&self, path: &str) -> Result<Option<&Value>, Error> {
86+
// Create a JSONPath selector
87+
let selector = Selector::new(path).map_err(|e| Error {
88+
msg: format!("{}", e),
89+
})?;
90+
91+
Ok(selector.find(&self.data).next())
92+
}
6793
}

0 commit comments

Comments
 (0)