Skip to content

Commit

Permalink
script: allow storing lua tables into state bag (#3005)
Browse files Browse the repository at this point in the history
Signed-off-by: Alexander Yastrebov <[email protected]>
  • Loading branch information
AlexanderYastrebov authored Apr 5, 2024
1 parent 3afe2ab commit cd74dda
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
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

0 comments on commit cd74dda

Please sign in to comment.