Przeglądaj źródła

feat: (MongoDB bridge) use ${var} syntax for MongoDB collection

This commit makes it possible to use the ${var} syntax to refer to
variables in the payload of the message in the collection field.
This makes it possible to select which collection to insert into
dynamically.

Fixes:
https://emqx.atlassian.net/browse/EMQX-9246
Kjell Winblad 2 lat temu
rodzic
commit
e808fef1e4

+ 23 - 1
lib-ee/emqx_ee_bridge/test/emqx_ee_bridge_mongodb_SUITE.erl

@@ -26,7 +26,8 @@ group_tests() ->
     [
         t_setup_via_config_and_publish,
         t_setup_via_http_api_and_publish,
-        t_payload_template
+        t_payload_template,
+        t_collection_template
     ].
 
 groups() ->
@@ -302,3 +303,24 @@ t_payload_template(Config) ->
         find_all(Config)
     ),
     ok.
+
+t_collection_template(Config) ->
+    {ok, _} = create_bridge(
+        Config,
+        #{
+            <<"payload_template">> => <<"{\"foo\": \"${clientid}\"}">>,
+            <<"collection">> => <<"${mycollectionvar}">>
+        }
+    ),
+    Val = erlang:unique_integer(),
+    ClientId = emqx_guid:to_hexstr(emqx_guid:gen()),
+    ok = send_message(Config, #{
+        key => Val,
+        clientid => ClientId,
+        mycollectionvar => <<"mycol">>
+    }),
+    ?assertMatch(
+        {ok, [#{<<"foo">> := ClientId}]},
+        find_all(Config)
+    ),
+    ok.

+ 8 - 1
lib-ee/emqx_ee_connector/src/emqx_ee_connector_mongodb.erl

@@ -35,8 +35,11 @@ on_start(InstanceId, Config) ->
         {ok, ConnectorState} ->
             PayloadTemplate0 = maps:get(payload_template, Config, undefined),
             PayloadTemplate = preprocess_template(PayloadTemplate0),
+            CollectionTemplateSource = maps:get(collection, Config),
+            CollectionTemplate = preprocess_template(CollectionTemplateSource),
             State = #{
                 payload_template => PayloadTemplate,
+                collection_template => CollectionTemplate,
                 connector_state => ConnectorState
             },
             {ok, State};
@@ -50,10 +53,14 @@ on_stop(InstanceId, _State = #{connector_state := ConnectorState}) ->
 on_query(InstanceId, {send_message, Message0}, State) ->
     #{
         payload_template := PayloadTemplate,
+        collection_template := CollectionTemplate,
         connector_state := ConnectorState
     } = State,
+    NewConnectorState = ConnectorState#{
+        collection => emqx_plugin_libs_rule:proc_tmpl(CollectionTemplate, Message0)
+    },
     Message = render_message(PayloadTemplate, Message0),
-    emqx_connector_mongo:on_query(InstanceId, {send_message, Message}, ConnectorState);
+    emqx_connector_mongo:on_query(InstanceId, {send_message, Message}, NewConnectorState);
 on_query(InstanceId, Request, _State = #{connector_state := ConnectorState}) ->
     emqx_connector_mongo:on_query(InstanceId, Request, ConnectorState).