How to define map schema in a plugin?

#1

Hello everyone:
I am a newbie to kong and I want to develop a plugin. In the plugin’s schema, i need to config a hash map to user, like this: {“027”->“hub”, “028”->“hen”, “035”->“heb” …} . In the kong document, the array must be an integer-indexed table. Now, i have to define like this:
local typedefs = require “kong.db.schema.typedefs”

return {
name = “request-province-routing”,
fields = {
{ run_on = typedefs.run_on_first },
{ protocols = typedefs.protocols_http },
{ config = {
type = “record”,
fields = {
{ tag = { type = “string”, required = true, default = “MessageID” }, },
{ city_start_index = { type = “integer”, required = true, default = 4 }, },
{ city_end_index = { type = “integer”, required = true, default = 6 }, },
{ header_name = { type = “string”, required = true, default = “X-Forwarded-Host” }, },
{ provinces = { type = “array”, required = true, default = {}, elements = { type = “string” }, },},
},
},
},
},
}

027=hub,028=hub,031=heb

local function to_map(provinces)
local s
for _, value in ipairs(provinces) do
s = find(value, “=”)
m_privinces[sub(value, 1, s-1)] = sub(value, s+1)
end

end

I know this is not good. any suggestion?

#2

any suggestion? thx a lot

#3
local map = {}
for _, value in ipairs(provinces) do
  local code, province = value:gmatch("^%d+)=(.+)$") -- untested pattern
  map[code] = province  -- you might want to use "map[tonumber(code)]=..." to drop the leading zero's
end

For more info on patterns see https://www.lua.org/pil/20.2.html .

Since you probably do not want to do this on each request, you should cache the created map with a controlled life time (to prevent memory leaks). You can use a weak table for that, indexed by the plugin configuration table.

Created here: https://github.com/Kong/kong/blob/0f2d77b678624b0383c0c80c01319cdee5b65cdb/kong/plugins/bot-detection/handler.lua#L26
used here: https://github.com/Kong/kong/blob/0f2d77b678624b0383c0c80c01319cdee5b65cdb/kong/plugins/bot-detection/handler.lua#L81-L85

hth