11#[ macro_use]
22extern crate redismodule;
33
4- use redismodule:: { Context , RedisResult , NextArg , REDIS_OK } ;
4+ use redismodule:: { Context , RedisResult , NextArg , REDIS_OK , RedisError } ;
55use redismodule:: native_types:: RedisType ;
66
77mod redisjson;
@@ -14,7 +14,6 @@ static REDIS_JSON_TYPE: RedisType = RedisType::new("RedisJSON");
1414pub enum SetOptions {
1515 NotExists ,
1616 AlreadyExists ,
17- None
1817}
1918
2019fn json_set ( ctx : & Context , args : Vec < String > ) -> RedisResult {
@@ -23,32 +22,32 @@ fn json_set(ctx: &Context, args: Vec<String>) -> RedisResult {
2322 let key = args. next_string ( ) ?;
2423 let _path = args. next_string ( ) ?; // TODO handle this path
2524 let value = args. next_string ( ) ?;
26- let option = match args. next ( ) {
27- Some ( op) => {
28- match op. as_str ( ) {
29- "NX" => SetOptions :: NotExists ,
30- "XX" => SetOptions :: AlreadyExists ,
31- _ => return Err ( "ERR syntax error" . into ( ) )
25+
26+ let set_option = args. next ( )
27+ . map ( |op| {
28+ match op. to_uppercase ( ) . as_str ( ) {
29+ "NX" => Ok ( SetOptions :: NotExists ) ,
30+ "XX" => Ok ( SetOptions :: AlreadyExists ) ,
31+ _ => Err ( RedisError :: Str ( "ERR syntax error" ) ) ,
3232 }
33- }
34- None => {
35- SetOptions :: None
36- }
37- } ;
33+ } )
34+ . transpose ( ) ?;
3835
3936 let key = ctx. open_key_writable ( & key) ;
37+ let current = key. get_value :: < RedisJSON > ( & REDIS_JSON_TYPE ) ?;
4038
41- match key. get_value :: < RedisJSON > ( & REDIS_JSON_TYPE ) ? {
42- Some ( ref mut doc) if option != SetOptions :: NotExists => {
39+ match ( current, set_option) {
40+ ( Some ( _) , Some ( SetOptions :: NotExists ) ) => REDIS_OK ,
41+ ( Some ( ref mut doc) , _) => {
4342 doc. set_value ( & value) ?;
4443 REDIS_OK
4544 }
46- None if option != SetOptions :: AlreadyExists => {
45+ ( None , Some ( SetOptions :: AlreadyExists ) ) => REDIS_OK ,
46+ ( None , _) => {
4747 let doc = RedisJSON :: from_str ( & value) ?;
4848 key. set_value ( & REDIS_JSON_TYPE , doc) ?;
4949 REDIS_OK
5050 }
51- _ => Ok ( ( ) . into ( ) )
5251 }
5352}
5453
0 commit comments