In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains the "advanced usage tutorial of Fizz Gateway gateway scripting function". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn the "advanced usage tutorial of Fizz Gateway gateway scripting function".
Create a service
# create aggregation API
# configuration input
When the verification fails, Fizz will put the reason for the verification failure (for example, the order ID cannot be empty) in the validateMsg field of the context
You can customize the format of the message returned to the caller, such as msgCode, message
Support for custom response headers
Support custom scripts to handle verification results
# configuration steps # basic information of configuration steps
# step instructions
An aggregation interface can contain multiple steps
A step can contain multiple requests (that is, calling multiple interfaces)
The steps are executed sequentially in series.
Multiple requests within a step are executed in parallel
# data conversion
Support for configuration of fixed values, referenced values and scripts
# fixed value
# script
# asterisk *
The asterisk wildcard can receive a reference value of the return object type, and the fields in the returned object will be merged into the target object.
Example: userInfo = {"userName": "Fizz", "userID": 1234}
# priority and overlay order
Fixed value
< 引用值 < 脚本 < 星号* 当一个字段配置了多种类型的值时按以上顺序覆盖,星号优先级最高 #引用值规范 # 获取入参请求头aaa的值input.request.headers.aaa# 获取入参请求体bbb字段的值input.request.body.bbb# 获取入参URL Query参数fff字段的值input.request.params.fff# 获取步骤1里request1的请求头ccc的值step1.request1.request.headers.ccc# 获取步骤1里request1的响应体ddd的值step1.request1.response.body.ddd# 获取步骤1结果里eee的值step1.result.eee 支持单值引用,如:string,int等 支持对象类型的引用 input: 表示调用方的输入数据,如H5页面提交上来的参数 stepN.requestN: 表示步骤N里调用接口N的相关参数 stepN.result: 表示步骤N的转换结果 #Fallback与预处理条件 Fallback: 当调用接口发生异常(如超时、网络或系统异常)可配置fallback方案: Stop: 终止请求并立即返回 Continue: 继续后续的操作,且要设置默认的fallback json 预处理: 根据条件判断是否要调用接口,脚本返回true时才调用接口 #配置步骤结果处理 配置返回给调用方的结果 支持配置响应头 支持配置响应体 支持自定脚本处理复杂的业务逻辑 #脚本#简介 Fizz 支持通过自定义脚本进行服务编排: 在 配置输入 中 通过 脚本校验 输入内容; 在 配置输出 中 通过 脚本 定义 输出内容,也可以细化到 某个输出字段的 脚本处理; 在 配置步骤 中 通过 脚本 定义 配置入参、配置响应 的返回内容; 在 结果校验 中 通过 脚本 完全自定义校验逻辑,校验输出内容。 Fizz支持 javascript 和 groovy 两种脚本语言,方便开发人员灵活的选择自己熟悉的语言进行服务编排。 其中, 如果使用javascript ,可以 通过 common 对象获取一系列工具函数,方便进行逻辑处理; 而在 groovy 中,所有的工具函数都挂载在 context下,你可以很方便的使用它们。 #脚本编写格式 #javascript 编写JavaScript脚本时,需要按照以下固定格式进行编写。 function name dyFunc 不可修改。 返回值只能是基本类型,如 string/number/boolean,object/array类型的必须通过JSON.stringify 序列化后返回。 Fizz 是通过调用 js引擎执行javascript脚本,然后捕获执行结果,只能获取基本的数据类型。 object/array类型捕获前,会调用原型上的toString 方法,得到的结果为 [object type] 的字符串,并非预期的数据,所以必须通过JSON.stringify()序列化为jsonString后再返回。 请勿在js 中使用document等api function dyFunc(paramsJsonStr) { var ctx = JSON.parse(paramsJsonStr)['context']; // do something... // return string/number/boolean/jsonString return JSON.stringify({});} #groovy 编写groovy脚本时,支持返回groovy支持的任何数据类型。 import com.alibaba.fastjson.JSONimport com.alibaba.fastjson.JSONArrayimport com.alibaba.fastjson.JSONObject// do something...// return any resultreturn result#配置输入--脚本校验 在 编辑服务编排接口时,允许在 配置输入 中,对输入的数据进行自定义的脚本校验,校验 请求头、请求体、query参数是否通过验证。 返回的验证结果,必须是一个 序列化后的 数组,且: 如果校验通过,则返回一个空数组; 如果校验不通过,将校验不通过的错误信息,push到数组中后返回。 参考示例: javascript function dyFunc(paramsJsonStr) { var ctx = JSON.parse(paramsJsonStr)['context']; // 获取聚合接口用户输入的数据 // 获取请求头 var token = common.getInputReqHeader(ctx, 'token'); // 获取请求参数 var account = common.getInputReqParam(ctx, 'account'); var validate = []; // 校验请求参数 if (!token) { // 将校验不通过的错误信息push到validate中 validate.push('缺少 token'); } if (!account) { validate.push('缺少 account'); } // 将 数组 validate 序列化后返回 // 空数组表示校验通过,非空表示校验不通过 return JSON.stringify(validate);} groovy // 获取聚合接口用户输入的数据// 获取请求头String token = context.getInputReqHeader('token')// 获取请求参数String account = context.getInputReqAttr('params').get('account')List validate = new LinkedList()// 校验请求参数if (token == null || token.trim().isEmpty()) { // 将校验不通过的错误信息add到validate中 validate.add('缺少 token')}if (account == null || account.trim().isEmpty()) { validate.add('缺少 account')}// 空数组表示校验通过,非空表示校验不通过return validate#配置输出 #输出 完整response 在 编辑服务编排接口时,允许在 配置输出 中,自定义输出结果。 对于返回结果,建议以 { 状态码, 请求信息,请求结果 } 的数据结构进行返回,示例如下: { "msgCode": 0, // 状态码 "message": "success", // 请求信息 "data": { // 请求结果 "count": 1 }} 当脚本内部执行时,检查到发生异常,需要终止请求,可在 响应的结果中, 添加_stopAndResponse: true 用于中断,直接将当前结果返回到用户端。 { "msgCode": 1, // 状态码 "message": "request error", "_stopAndResponse": true // 终止请求并返回响应结果} 配置输出脚本示例: // javascript脚本函数名不能修改function dyFunc(paramsJsonStr) { var context = JSON.parse(paramsJsonStr)['context']; var data = common.getStepRespBody(context, 'step2', 'request1', 'data'); // do something // 自定义 返回结果,如果返回的Object里含有_stopAndResponse=true字段时将会终止请求并把脚本结果响应给客户端(主要用于有异常情况要终止请求的场景) var result = { // 对于result 内的数据结构无其他特殊要求,msgCode/message/data字段仅做示例 // _stopAndResponse: true, msgCode: '0', message: '', data: data }; // 返回结果为Array或Object时要先转为json字符串 return JSON.stringify(result);} #单个字段 输出脚本处理 在 编辑服务编排接口时,允许在 配置输出 中,通过脚本处理,自定义单个字段的值。 在字段配置中,选择 脚本后,即可通过脚本 配置 单个字段的值。 这里的脚本执行的结果只赋值给单个字段。/ / javascript script function name cannot be modified function dyFunc (paramsJsonStr) {var context = JSON.parse (paramsJsonStr) ['context']; var token = common.getStepRespBody (context,' step2', 'request1',' token'); / / do something var memberId = parseToken (token); return memberId;} # configuration steps
Same as the above configuration input-script checksum _ _ configuration output _ _.
# result check
Result check refers to the verification of the data that is finally returned to the client.
The validation result returned must be a serialized array, and:
If the check passes, an empty array is returned
If the verification fails, the failed error message will be verified and returned after push to the array.
Reference example:
Javascript
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; / get the data entered by the user of the aggregation API / / get the request header var token = common.getInputReqHeader (ctx,' token'); / / get the request parameter var account = common.getInputReqParam (ctx, 'account'); var validate = [] / / Verification request parameter if (! token) {/ / push the failed error message to validate validate.push ('missing token');} if (! account) {validate.push (' missing account') } / / return / / empty array after serialization of array validate indicates that the check passed, and non-empty means that the check does not pass return JSON.stringify (validate);}
Groovy
/ / get the data entered by the user of the aggregation API / / get the request header String token = context.getInputReqHeader ('token') / / get the request parameter String account = context.getInputReqAttr (' params'). Get ('account') List validate = new LinkedList () / / verify the request parameter if (token = = null | | token.trim (). IsEmpty ()) {/ / add the failed error message to validate in validate. Add ('missing token')} if (account = = null | | account.trim () .isEmpty ()) {validate.add (' missing account')} / / empty array indicates that the check passed Non-null means that the check fails the context in the return validate#javascript script
The context in the javascript script is in scope only and is passed in as the first input parameter of function dyFunc (paramsJsonStr) {}.
Function dyFunc (paramsJsonStr) {/ / the paramsJsonStr passed in is only a string, which needs to be serialized through JSON.parse to get `context` var ctx = JSON.parse (paramsJsonStr) ['context']; / / do something... }
Context data structure description:
Interface context {debug: boolean; / / whether DEBUG mode elapsedTimes: elapsedTime []; / / time consuming input of each operation: {/ / customer input and the returned result of the API request: {/ / request path: string; / / request path method: string; / / request method POST/GET/PUT/DELETE/... Headers: {[head: string]: any;}; / / request header body: {[field: string]: any;}; / / request body params: {[param: string]: any;}; / / response body} Response: {/ / response headers: {[head: string]: any;}; / / response header body: {[field: string]: any;}; / / response of the polymerization interface of the response body};} [stepName: string]: {/ / step [requestName: string]: {/ / API request: {/ request related parameters url: string; / / request path method: string; / / request method POST/GET/PUT/DELETE/... Headers: {[head: string]: any;}; / / request header body: {[body: string]: any;}; / / request body params: {[param: string]: any;} / / response body}; response: {/ / response headers: {[head: string]: any;}; / / response header body: {[field: string]: any }; / / response body};}; result: string | number | boolean; / / object/array needs to be serialized using JSON.stirngify} interface elapsedTime {[acticeName: string]: number; / / Operation name: time consuming}
To facilitate the use of context in scripts, we provide utility functions for javascript and groovy scripts.
# tool function-javascript
Common.getInputReq (ctx):
Get the request object in the context client
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var req = common.getInputReq (ctx); var path = req.path; / / request path var method = req.method; / / request method var headers = req.headers; / / request header var body = req.body; / / request body var params = req.params; / / request parameters / / do something... / / return anything string return';}
Ctx: context
Common.getStepReq (ctx, stepName, requestName):
Get the request object of the request interface in the context step
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var req = common.getStepReq (ctx,' step1', 'request1'); var url = req.url; / / request path var method = req.method; / / request method var headers = req.headers; / / request header var body = req.body; / / request body var params = req.params / / request parameters / / do something... / / return anything string return';}
Ctx: context
StepName: step name in the configuration step
RequestName: request name corresponding to the stepName in the configuration step
Common.getStepResp (ctx, stepName, requestName)
Gets the response object of the request interface in the context step
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var stepResp = common.getStepResp (ctx,' step1', 'request1'); / / do something... / / return anything string return';}
Ctx: context
StepName: step name in the configuration step
RequestName: request name corresponding to the stepName in the configuration step
Common.getInputReqHeader (ctx, headerName)
Get client request header
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var contentType = common.getInputReqHeader (ctx,' content-type'); / / do something... / / return anything string return';}
Ctx: context
HeaderName: request header field name [optional]. Return all request headers if not passed
Common.getInputReqParam (ctx, paramName)
Get client URL request parameters (query string)
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var page = common.getInputReqParam (ctx,' page'); / / do something... / / return anything string return';}
Ctx: context
ParamName URL parameter name [optional]. If not passed, all request parameters are returned.
Common.getInputReqBody (ctx, field)
Get the client request body
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var page = common.getInputReqBody (ctx,' page'); / / do something... / / return anything string return';}
Ctx: context
Field field name [optional]. If not passed, the entire request body is returned.
Common.getInputRespHeader (ctx, headerName)
Gets the response header returned to the client
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var page = common.getInputRespHeader (ctx,' content-type'); / / do something... / / return anything string return';}
Ctx: context
HeaderName response header field name [optional]. Return all response headers if not passed.
Common.getInputRespBody (ctx, field)
Gets the response body returned to the client
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var page = common.getInputReqBody (ctx,' page'); / / do something... / / return anything string return';}
Ctx: context
Field field name [optional]. If not passed, the entire response body is returned.
Common.getStepReqHeader (ctx, stepName, requestName, headerName)
Gets the request header of the interface called in the step
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var contentType = common.getStepReqHeader (ctx,' step1', 'request1',' content-type'); / / do something... / / return anything string return';}
Ctx context [required]
StepName step name [required]
The interface name of the requestName request [required]
HeaderName request header field name [optional]. Return all request headers if not passed
Common.getStepReqParam (ctx, stepName, requestName, paramName)
Gets the URL parameter of the interface called in the step
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var page = common.getStepReqParam (ctx,' step1', 'request1',' page'); / / do something... / / return anything string return';}
Ctx context [required]
StepName step name [required]
The interface name of the requestName request [required]
ParamName URL parameter name [optional]. If not passed, all URL parameters are returned.
Common.getStepReqBody (ctx, stepName, requestName, field)
Gets the request body of the interface called in the step
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var page = common.getStepReqBody (ctx,' step1', 'request1',' page'); / / do something... / / return anything string return';}
Ctx context [required]
StepName step name [required]
The interface name of the requestName request [required]
Field field name [optional]. If not passed, the entire request body is returned.
Common.getStepRespHeader (ctx, stepName, requestName, headerName)
Gets the response header of the interface called in the step
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var contentType = common.getStepRespHeader (ctx,' step1', 'request1',' content-type'); / / do something... / / return anything string return';}
Ctx context [required]
StepName step name [required]
The interface name of the requestName request [required]
HeaderName response header field name [optional]. Return all response headers if not passed.
Common.getStepRespBody (ctx, stepName, requestName, field)
Gets the response header of the interface called in the step
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var page = common.getStepRespBody (ctx,' step1', 'request1',' page'); / / do something... / / return anything string return';}
Ctx context [required]
StepName step name [required]
The interface name of the requestName request [required]
Field field name [optional]. Return the entire response header if it is not passed.
Common.getStepResult (ctx, stepName, field)
Get the result of the step
Function dyFunc (paramsJsonStr) {var ctx = JSON.parse (paramsJsonStr) ['context']; var list = common.getStepResult (ctx,' step1', 'list'); / / do something... / / return anything string return';}
Ctx context [required]
StepName step name [required]
Field field name [optional]. If not passed, the result object of the entire step is returned.
# tool function-groovy
Context.getInputReq ()
Get the request object in the context client
Map req = context.getInputReq ()
Context.getStepReq (stepName, requestName):
Get the request object of the request interface in the context step
Map req = context.getStepReq ('step1',' request1')
StepName: step name in the configuration step
RequestName: request name corresponding to the stepName in the configuration step
Context.getStepResp (stepName, requestName)
Gets the response object of the request interface in the context step
StepName: step name in the configuration step
RequestName: request name corresponding to the stepName in the configuration step
Context.getInputReqHeader (headerName)
Get client request header
HeaderName: request header field name [optional]. Return all request headers if not passed
Context.getInputReqParam (paramName)
Get client URL request parameters (query string)
ParamName URL parameter name [optional]. If not passed, all request parameters are returned.
Context.getInputReqBody (field)
Get the client request body
Field field name [optional]. If not passed, the entire request body is returned.
Context.getInputRespHeader (headerName)
Gets the response header returned to the client
HeaderName response header field name [optional]. Return all response headers if not passed.
Context.getInputRespBody (field)
Gets the response body returned to the client
Field field name [optional]. If not passed, the entire response body is returned.
Context.getStepReqHeader (ctx, stepName, requestName, headerName)
Gets the request header of the interface called in the step
StepName step name [required]
The interface name of the requestName request [required]
HeaderName request header field name [optional]. Return all request headers if not passed
Context.getStepReqParam (stepName, requestName, paramName)
Gets the URL parameter of the interface called in the step
StepName step name [required]
The interface name of the requestName request [required]
ParamName URL parameter name [optional]. If not passed, all URL parameters are returned.
Context.getStepReqBody (stepName, requestName, field)
Gets the request body of the interface called in the step
StepName step name [required]
The interface name of the requestName request [required]
Field field name [optional]. If not passed, the entire request body is returned.
Context.getStepRespHeader (stepName, requestName, headerName)
Gets the response header of the interface called in the step
StepName step name [required]
The interface name of the requestName request [required]
HeaderName response header field name [optional]. Return all response headers if not passed.
Context.getStepRespBody (stepName, requestName, field)
Gets the response header of the interface called in the step
StepName step name [required]
The interface name of the requestName request [required]
Field field name [optional]. Return the entire response header if it is not passed.
Context.getStepResult (stepName, field)
Get the result of the step
StepName step name [required]
Field field name [optional]. If not passed, the result object of the entire step is returned.
# throw an exception
When you want to abort a request in a script, you can do it in the following ways
If an object is returned and the object contains a property whose _ stopAndResponse equals true, Fizz terminates the subsequent operation and returns the object to the caller.
# redirect
Redirection can be achieved through a script, which returns an object that contains both _ stopAndResponse=true and _ redirectUrl attributes, and the target URL,Fizz whose value of _ redirectUrl is redirected terminates subsequent operations and redirects. An example JavaScript script is as follows:
# online testing
Support debug mode, can be used in both test interface and official interface, reissue after modification can take effect in real time, and request log and message will be printed in debug mode, mainly used to troubleshoot online problems.
# script execution exception
When the script executes an exception, the exception information is recorded in the context.
ExceptionMessage exception information
ExceptionStacks exception stack information
Script data that exceptionData causes an exception
/ / context data structure design / / context, which is used to save customer input and output and the input and output results of each step var context = {/ / whether DEBUG mode debug:false, / / exception info exceptionMessage: ", exceptionStacks:", exceptionData: ", / / such as script source code that cause exception / /. Other fields}
Add returnContext=true to the request to return the context context. Sample exception information:
Import and export is mainly used to synchronize interface configuration between different environments, test it in the test environment after the development environment is configured, and release it to the production environment after testing.
# publish | go offline and review
Currently released | there are two entries for offline application.
Batch release: publish the interfaces in the release list in batch
Batch rollback: batch rollback of the interfaces in the publishing order
Publishing: publishing to gateway in real time
Rollback: rollback to any version of history is supported. You can specify a version in the release history to roll back.
Offline: delete the interface from the gateway and go online again through the publishing feature in the background
# release process description
The permissions to apply for release, review, release and offline functions can be flexibly assigned to different roles as needed, for example, developers can only apply for release, superior leaders review, and operators or testers perform release, rollback or offline. Application release, review, release and offline functions can also be assigned to developers in development, testing, and pre-production environments to facilitate developers' debugging.
Thank you for reading. The above is the content of the "Advanced usage tutorial of Fizz Gateway Gateway scripting function". After the study of this article, I believe you have a deeper understanding of the advanced usage tutorial of Fizz Gateway Gateway scripting function, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.