emqx_rewrite_api.erl 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020-2021 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("typerefl/include/types.hrl").
  19. -export([api_spec/0, paths/0, schema/1]).
  20. -export([topic_rewrite/2]).
  21. -define(MAX_RULES_LIMIT, 20).
  22. -define(EXCEED_LIMIT, 'EXCEED_LIMIT').
  23. -import(emqx_mgmt_util, [ object_array_schema/1
  24. , object_array_schema/2
  25. , error_schema/2
  26. , properties/1
  27. ]).
  28. api_spec() ->
  29. emqx_dashboard_swagger:spec(?MODULE, #{check_schema => true, translate_body => true}).
  30. paths() ->
  31. ["/mqtt/topic_rewrite"].
  32. schema("/mqtt/topic_rewrite") ->
  33. #{
  34. operationId => topic_rewrite,
  35. get => #{
  36. tags => [mqtt],
  37. description => <<"List rewrite topic.">>,
  38. responses => #{
  39. 200 => hoconsc:mk(hoconsc:array(hoconsc:ref(emqx_modules_schema, "rewrite")),
  40. #{desc => <<"List all rewrite rules">>})
  41. }
  42. },
  43. put => #{
  44. description => <<"Update rewrite topic">>,
  45. requestBody => hoconsc:mk(hoconsc:array(hoconsc:ref(emqx_modules_schema, "rewrite")),#{}),
  46. responses => #{
  47. 200 => hoconsc:mk(hoconsc:array(hoconsc:ref(emqx_modules_schema, "rewrite")),
  48. #{desc => <<"Update rewrite topic success.">>}),
  49. 413 => emqx_dashboard_swagger:error_codes([?EXCEED_LIMIT], <<"Rules count exceed max limit">>)
  50. }
  51. }
  52. }.
  53. topic_rewrite(get, _Params) ->
  54. {200, emqx_rewrite:list()};
  55. topic_rewrite(put, #{body := Body}) ->
  56. case length(Body) < ?MAX_RULES_LIMIT of
  57. true ->
  58. ok = emqx_rewrite:update(Body),
  59. {200, emqx_rewrite:list()};
  60. _ ->
  61. Message = iolist_to_binary(io_lib:format("Max rewrite rules count is ~p", [?MAX_RULES_LIMIT])),
  62. {413, #{code => ?EXCEED_LIMIT, message => Message}}
  63. end.