Leight
Leight

Reputation: 5

Share Backend Response to used in lua script Krakend

Introduction

I'm newbie in krakend, i have two backend that accessed sequential, first access host let's say a.com to get an id from there, then the second backend have dynamic host depends on the id from a.com response if the id is 1 then the host for the second backend is b if the id is 2 then the host for the second backend is c

Question

How to deliver the response from a.com to next backend request

{
  "$schema": "https://www.krakend.io/schema/krakend.json",
  "version": 3,
  "name": "Test Proxying & Microservices",
  "timeout": "3000ms",
  "cache_ttl": "300s",
  "endpoints": [
    {
      "endpoint": "/protected/{path}",
      "extra_config": {
        "proxy": {
          "sequential": true
        }
      },
      "backend": [
        {
          "encoding": "no-op",
          "@comment": "Authentication Service",
          "url_pattern": "/api/v1/allocations",
          "method": "GET",
          "host": ["https://a.com"],
          "disable_host_sanitize": false,
          "extra_config": {
            "modifier/lua-backend": {
              "sources": ["authz.lua"],
              "allow_open_libs": true,
              "post": "print('Auth Response'); local r = response.load(); r:headers('Accept','*/*'); print(r);authz_proxy_decorator(r)"
            }
          }
        },
        {
          "@comment": "Genesist Base",
          "encoding": "no-op",
          "url_pattern": "/{path}",
          "host": ["https://{dynamic_host_from_resp0_next_host}.com"],
          "extra_config": {
            "modifier/lua-backend": {
              "sources": ["authz.lua"],
              "pre": "print('Backend response, pre-logic:'); local r = request.load(); print(r:headers('Accept')); get_previous_code(r);"
            }
          }
        }
      ]
    }
  ]
}

I expect if a.com response {"host": c} then the next backend will be c.com

Upvotes: 0

Views: 261

Answers (1)

Albert Garcia
Albert Garcia

Reputation: 187

Yes, it is possible to achieve this using KrakenD's dynamic routing capabilities, which is an Enterprise-only feature. With dynamic routing, both the host and the url_pattern of a backend can be dynamically set based on information from parameters, the request, or a previous response when using a sequential proxy.

You can read more about the dynamic routing capabilities of KrakenD Enterprise at: https://www.krakend.io/docs/enterprise/endpoints/dynamic-routing/

Additionally, you can find an example, in this case on how to set the url_pattern dynamically, on this repository: https://github.com/krakend/examples/tree/main/multiple_post/enterprise

Hope this helps!

Upvotes: 0

Related Questions