@vbNoName

Как работает данный код?

Есть два файла

-module(api_myusacorporation_com_app).
    -behaviour(application).
    
    -export([start/2]).
    -export([stop/1]).
    
    -import(cowboy_routes_tree, [rt/1]).
    
    start(_Type, _Args) ->
      lager:debug("Some message with a term: ~p", [config:get(mysql_host)]),
      emysql:add_pool(myusacorporation_sql_pool, [{size, 10},
                                                  {host, config:get(mysql_host)},
                                                  {user, config:get(mysql_user)},
                                                  {database, config:get(mysql_db)},
                                                  {password, config:get(mysql_password)},
                                                  {encoding, utf8}]),
      sql_queries:prepare_queries(),
      Dispatch = cowboy_router:compile([
                                        {'_', rt([{"/v1",
                                                   [
                                                    {{"/orders", orders_handler, []},
                                                     [
                                                      {"/:order_id", order_handler, []},
                                                      {"/:order_id/steps", order_steps_handler, []},
                                                      {"/steps/:step_id", order_step_handler, []},
                                                      {"/history/:item_id", order_history_item_handler, []},
                                                      {"/:order_id/history", sublevel_collection_handler, {order, order_id, order_history}},
                                                      {"/:order_id/details", order_details_handler, []},
                                                      {"/:order_id/is-favorite", order_is_favorite_handler, []},
                                                      {"/:order_id/unused-steps", order_unused_steps_handler, []},
                                                      {"/:order_id/payments/[:payment_id]", order_payments_handler, []}
                                                     ]},
                                                    {{"/companies", toplevel_collection_handler, company},
                                                     [
                                                      {"/:company_id", company_handler, []},
                                                      {"/:company_id/orders", sublevel_collection_handler, {company, company_id, company_order}},
                                                      {"/:company_id/entities", sublevel_collection_handler, {company, company_id, company_entity}},
                                                      {"/:company_id/accounts", sublevel_collection_handler, {company, company_id, company_client}}
                                                     ]},
                                                    {{"/entities", toplevel_collection_handler, entity},
                                                     [
                                                      {"/:entity_id", entity_handler, []},
                                                      {"/:entity_id/dbas", sublevel_collection_handler, {entity, entity_id, entity_dba}}
                                                     ]},
                                                    {"/payments",
                                                     [
                                                      {"/:payment_id", payments_handler, []}
                                                     ]},
                                                    {"/healthometer",
                                                     [
                                                      {"/icons", healthometer_handler, []},
                                                      {"/daily-history", healthometer_daily_history_handler, []}
                                                     ]},
                                                    {"/ip",
                                                     [
                                                      {"/:ip", ip_handler, []}
                                                     ]},
                                                    {"/fees",
                                                     [
                                                      {"/:fee_mnemonic", fee_handler, []}
                                                     ]},
                                                    {"/office",
                                                     [
                                                      {"/fees", office_fees_handler, []},
                                                      {"/idtypes", office_idtypes_handler, []},
                                                      {"/address-providers", office_address_providers, []},
                                                      {"/address-providers/:provider_id", office_address_provider_handler, []},
                                                      {"/addresses", office_addresses_handler, []},
                                                      {"/addresses/:address_id", office_address_handler, []},
                                                      {{"/accounts", office_accounts_handler, []},
                                                       [
                                                        {"/:account_id", office_account_handler, []},
                                                        {"/:account_id/history", office_account_history_handler, []},
                                                        {"/history/:item_id", office_account_history_item_handler, []},
                                                        {"/:account_id/steps", office_account_steps_handler, []},
                                                        {"/steps/:step_id", office_account_step_handler, []},
                                                        {"/:account_id/details", office_account_details_handler, []},
                                                        {"/:account_id/unused-steps", office_account_unused_steps_handler, []}
                                                       ]}
                                                     ]},
                                                    {"/partners",
                                                     [
                                                      {"/partners/:partner_website", partners_handler, []}
                                                     ]},
                                                    {{"/clients", toplevel_collection_handler, client},
                                                     [
                                                      {"/:client_id", client_handler, []}
                                                     ]}
                                                   ]}
                                                 ])}
                                       ]),
      {ok, _} = cowboy:start_http(http, 100, [{port, 8071}], [
                                                              {env, [{dispatch, Dispatch}]}
                                                             ]),
      api_myusacorporation_com_sup:start_link().
    
    stop(_State) ->
      ok.


второй

-module(sublevel_collection_handler).
    
    -export([init/2]).
    -export([allowed_methods/2]).
    -export([content_types_provided/2]).
    -export([content_types_accepted/2]).
    -export([resource_exists/2]).
    
    -export([render_json/2]).
    -export([create_from_json/2]).
    
    init(Req, Opts) ->
      {cowboy_rest, Req, Opts}.
    
    allowed_methods(Req, State) ->
      {[<<"GET">>, <<"POST">>], Req, State}.
    
    content_types_provided(Req, State) ->
      {[{{<<"application">>, <<"json">>, []}, render_json}], Req, State}.
    
    content_types_accepted(Req, State) ->
      {[{{<<"application">>, <<"json">>, []}, create_from_json}],
       Req, State}.
    
    resource_exists(Req, {TopRes, TopResIdName, Res}) ->
      case cowboy_req:binding(TopResIdName, Req) of
        undefined ->
          {false, Req, index};
        TopResId -> case TopRes:exists(TopResId) of
                      {false, FOI} -> {false, Req, FOI};
                      {true, TopResId1} ->
                        {true, Req, {TopResId1, Res}}
                    end
      end.
    
    render_json(Req, State) ->
      {Orders, Total} = read(Req, State),
      {jsonx:encode([{data, Orders}, {total, Total}]), Req, State}.
    
    create_from_json(Req, {TopResId, Res}) ->
      {ok, Body, _Req1} = cowboy_req:body(Req),
      Data = jsonx:decode(Body, [{format, proplist}]),
      lager:debug("JSON: ~p", [Data]),
      Id = Res:create(TopResId, Data),
      M = Res:read(Id),
      Req2 = cowboy_req:set_resp_body(jsonx:encode(M), Req),
      {true, Req2, {TopResId, Res}}.
    
    read(Req, {TopResId, Res}) ->
      QS = base_handler:parse_qs(Req),
      {Start, Limit, Sort, Filter} = base_handler:get_collection_params(QS),
      Res:read_with_total_for(TopResId, Start, Limit, Sort, Filter).


из первого по url
/:order_id/history
/:company_id/orders
/:company_id/entities
/:company_id/accounts

во второй "sublevel_collection_handler" передаются какие данные. Какие данные передаются и что происходит во втором файле?
  • Вопрос задан
  • 186 просмотров
Пригласить эксперта
Ответы на вопрос 1
@alkanenko
https://ninenines.eu/docs/en/cowboy/2.0/manual/cow... - чтобы понять, что такое state machine в Эрланг можно загуглить gen_statem (или gen_fsm старый вариант).
Дергается init и пошло-поехало
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы