emqx_rewrite_api.erl 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020-2022 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_rewrite_api).
  17. -behaviour(minirest_api).
  18. -include_lib("hocon/include/hoconsc.hrl").
  19. -include_lib("typerefl/include/types.hrl").
  20. -include("emqx_modules.hrl").
  21. -export([api_spec/0, paths/0, schema/1]).
  22. -export([topic_rewrite/2]).
  23. -define(MAX_RULES_LIMIT, 20).
  24. -define(EXCEED_LIMIT, 'EXCEED_LIMIT').
  25. api_spec() ->
  26. emqx_dashboard_swagger:spec(?MODULE).
  27. paths() ->
  28. ["/mqtt/topic_rewrite"].
  29. schema("/mqtt/topic_rewrite") ->
  30. #{
  31. 'operationId' => topic_rewrite,
  32. get => #{
  33. tags => ?API_TAG_MQTT,
  34. description => ?DESC(list_topic_rewrite_api),
  35. responses => #{
  36. 200 => hoconsc:mk(
  37. hoconsc:array(hoconsc:ref(emqx_modules_schema, "rewrite")),
  38. #{desc => ?DESC(list_topic_rewrite_api)}
  39. )
  40. }
  41. },
  42. put => #{
  43. description => ?DESC(update_topic_rewrite_api),
  44. tags => ?API_TAG_MQTT,
  45. 'requestBody' => hoconsc:mk(
  46. hoconsc:array(
  47. hoconsc:ref(emqx_modules_schema, "rewrite")
  48. ),
  49. #{}
  50. ),
  51. responses => #{
  52. 200 => hoconsc:mk(
  53. hoconsc:array(hoconsc:ref(emqx_modules_schema, "rewrite")),
  54. #{desc => ?DESC(update_topic_rewrite_api)}
  55. ),
  56. 413 => emqx_dashboard_swagger:error_codes(
  57. [?EXCEED_LIMIT],
  58. ?DESC(update_topic_rewrite_api_response413)
  59. )
  60. }
  61. }
  62. }.
  63. topic_rewrite(get, _Params) ->
  64. {200, emqx_rewrite:list()};
  65. topic_rewrite(put, #{body := Body}) ->
  66. case length(Body) < ?MAX_RULES_LIMIT of
  67. true ->
  68. ok = emqx_rewrite:update(Body),
  69. {200, emqx_rewrite:list()};
  70. _ ->
  71. Message = iolist_to_binary(
  72. io_lib:format("Max rewrite rules count is ~p", [?MAX_RULES_LIMIT])
  73. ),
  74. {413, #{code => ?EXCEED_LIMIT, message => Message}}
  75. end.