Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

script: allow storing lua tables into state bag #3005

Merged
merged 1 commit into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/reference/scripts.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ Path("/api/:id") -> lua("function request(ctx, params); print(ctx.path_param.id)

## StateBag

The state bag can be used to pass values from one filter to another in the same
chain. It is shared by all filters in one request.
The state bag can be used to pass string, number and table values from one filter to another in the same
chain. It is shared by all filters in one request (lua table values are only available to lua filters).
```lua
function request(ctx, params)
-- the value of "mykey" will be available to all filters in the chain now:
Expand Down
4 changes: 4 additions & 0 deletions script/script.go
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,8 @@ func getStateBag(f filters.FilterContext) func(*lua.LState) int {
s.Push(lua.LNumber(res))
case float64:
s.Push(lua.LNumber(res))
case *lua.LTable:
s.Push(res) // load *lua.LTable as is
default:
return 0
}
Expand All @@ -626,6 +628,8 @@ func setStateBag(f filters.FilterContext) func(*lua.LState) int {
res = string(val.(lua.LString))
case lua.LTNumber:
res = float64(val.(lua.LNumber))
case lua.LTTable:
res = val // store *lua.LTable as is
default:
// TODO(sszuecs): https://github.com/zalando/skipper/issues/1487
// s.RaiseError("unsupported state bag value type %v, need a string or a number", val.Type())
Expand Down
18 changes: 11 additions & 7 deletions script/script_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -822,18 +822,22 @@ func ExampleGetMissingStateBag() {
// nil
}

const SetUnsupportedStateBag = `
const SetStateBagTable = `
function request(ctx, params)
ctx.state_bag.unsupported = {}
print("ok")
end`
ctx.state_bag.table = {foo="bar"}
end

function response(ctx, params)
print(ctx.state_bag.table.foo)
end
`

func ExampleSetUnsupportedStateBag() {
func ExampleSetStateBagTable() {
runExample(&testContext{
script: SetUnsupportedStateBag,
script: SetStateBagTable,
})
// Output:
// ok
// bar
}

func newFilter(opts LuaOptions, script string, params ...string) (filters.Filter, error) {
Expand Down
Loading