flomesh-io / pipy

Pipy is a programmable proxy for the cloud, edge and IoT.
https://flomesh.io/pipy
Other
743 stars 70 forks source link

whether it can be support javascript eval expression #152

Closed sixinyiyu closed 1 year ago

sixinyiyu commented 1 year ago

Discussion

a config.json

[
  {
   "k": "abc",
   "v": "e.head.headers['user-agent'] + e.head.headers['host']"
  }
[

eg:

((
  conf= pipy.solve('config.json'),
) => pipy()

.pipeline()
 .handleMessageStart(
  e => (
    (headers = e.head.headers)  =>(
           conf.forEach(one => e.head.headers[one.k] = evel(one.v))
    )
   )()
 )()

result:

headers:
user-agent: chrome
host: 1.1.1.1
abc: chromd1.1.1.1
pajama-coder commented 1 year ago

This can be done with pipy.solve(). The difference though is pipy.solve() evaluates from a source file while the JavaScript-esque eval() evaluates from a string. That means you can't have JS expressions as strings in JSON like in the example you show above, but instead, you can have JS expressions in your config if it were a config.js rather than a config.json:

[
  {
   k: "abc",
   v: (e) => e.head.headers['user-agent'] + e.head.headers['host'],
  }
]

As such, you can make calls to that function in your pipelines:

((
  conf = pipy.solve('config.js'),
) => pipy()

.pipeline()
 .handleMessageStart(
  e => (
    (headers = e.head.headers)  =>(
           conf.forEach(({ k, v }) => e.head.headers[k] = v(headers))
    )
   )()
 )()
sixinyiyu commented 1 year ago

thanks, I will try.