DataPower API Gateway 에서 GatewayScript 및 XSLT 정책의 컨텍스트 변수 사용
API 어셈블리의 GatewayScript 및 XSLT 정책에 대한 코드에서 API 컨텍스트 변수를 사용하여 API 호출 시 생성되는 메시지에 대해 작업할 수 있습니다.
모든 API 컨텍스트 변수는 JSON과 유사한 트리에 저장됩니다. 각 컨텍스트 변수는 이 트리에 있는 노드입니다. 리프가 아닌 노드는 오브젝트 또는 배열일 수 있지만 리프 노드는 숫자, 문자열, 부울 또는 문서일 수 있습니다. 문서에는 XML 문서, BLOB, 스트림 또는 다른 JSON 문서가 포함될 수 있습니다.
각 컨텍스트 변수에는 이름과 값이 있습니다. GatewayScript 및 XSLT API를 사용하는 경우 이름으로 컨텍스트 변수에 액세스할 수 있습니다. 점 표기법은 JSON과 유사한 트리에서 해당 노드의 위치를 반영하여 컨텍스트 변수에 액세스하는 데 사용됩니다(예:request.headers.Host). 노드 이름에 특수 문자가 포함되어 있는 경우 대괄호 표기법이 지원됩니다(예: request.headers['Content-Type']).
GatewayScript 정책의 경우 DataPower® API Gateway 에 대한 모든 API가 글로벌 모듈인 context 모듈에 있습니다. 따라서 직접 context 모듈에 액세스할 수 있으며
먼저 require() 함수를 사용할 필요가 없습니다.
XSLT 정책의 경우 API가
http://www.ibm.com/xmlns/datapower/2017/11/apigateway 네임스페이스에
있습니다. 이러한 API를 사용하려면 이 네임스페이스를 선언해야 합니다.
컨텍스트 변수 액세스
- GatewayScript 예제
client.app.id컨텍스트 변수를 읽습니다.var clientID = context.get('client.app.id');컨텍스트 변수의 값을 설정합니다.
결과 트리의 구조는 다음과 같습니다.context.set('my.vars.amount', 100);{ "my": { "vars": { "amount": 100 } } }my.vars노드와 이 노드의 모든 하위 노드를 삭제합니다.
결과 트리의 구조는 다음과 같습니다.context.clear('my.vars');{ "my": { } }- XSLT 예제
client.app.id컨텍스트 변수를 읽습니다.<xsl:variable name="clientID" select="apigw:get-variable('client.app.id')"/>컨텍스트 변수의 값을 설정합니다.
결과 트리의 구조는 다음과 같습니다.<apigw:set-variable name="'my.vars.amount'" value="100"/>{ "my": { "vars": { "amount": 100 } } }my.vars노드와 이 노드의 모든 하위 노드를 삭제합니다.
결과 트리의 구조는 다음과 같습니다.<apigw:clear-variable name="'my.vars'"/>{ "my": { } }
페이로드 정보
request: 원래 페이로드에 대한 정보를 보유합니다.request메시지는 읽기 전용 오브젝트입니다.message: 현재 페이로드에 대한 정보를 보유합니다.
headers 및 body 특성이 있습니다. 현재 페이로드의 경우 message 메시지 오브젝트에 variables 및 status 특성과
어셈블리 실행 중에 작성된 기타 특성이 있을 수 있습니다.{
"headers": {
"Content-Type": "application/xml",
"X-Client-ID": "1234567890"
},
"variables": {
"amount": 123,
"name": "xyz"
},
"status": {
"code": 200,
"reason": "OK"
},
"body": <XML/Blob/Stream/JSON Document>
}메시지 헤더 조작
- GatewayScript 예제
- 헤더를 삭제합니다.
context.message.header.remove('X-My-Header');헤더를 읽습니다.var reqType = context.request.header.get('Content-Type'); var currType = context.message.header.get('Content-Type');헤더를 설정합니다.context.message.header.set('Content-Type', 'application/json');헤더를 반복합니다.var reqHdrs = context.request.headers; for (var h in reqHdrs) { console.log('>>> Reading the request header: ', h, '=', reqHdrs[h]); } var currHdrs = context.message.headers; for (var h in currHdrs) { console.log('>>> Reading the current header: ', h, '=', currHdrs[h]); }headersContext라는 메시지 컨텍스트를 작성하려면, 컨텍스트가 없는 경우 값true로HelloWorld라는 부울 컨텍스트 변수에 추가하십시오.var ctx = context.getMessage("headersContext") || context.createMessage("headersContext"); ctx.setVariable('HelloWorld', true);setVariable호출은 변수를headersContext.variables.HelloWorld로 작성합니다. 후속switch정책의 조건문은headersContext.HelloWorld대신headersContext.variables.HelloWorld를 확인해야 합니다.후속gatewayscript정책에서 컨텍스트 변수를 읽으려면, 다음 호출을 사용하십시오.ctx.getVariable("HelloWorld")참고: IBM® API Connect Version 5.0또는 DataPower Gateway (v5 compatible)에서 DataPower API Gateway로 API를 마이그레이션하거나 DataPower API Gateway에 대한 새 API를 구성하는 경우 컨텍스트 변수 액세스에 설명된 컨텍스트 변수 메커니즘을 사용하지 않고 메시지 컨텍스트를 작성하는 것이 선호되는 옵션입니다. 마이그레이션의 경우 IBM API Connect Version 5.0의 동작과 가장 밀접하게 일치하며setVariable및getVariable호출은 수정 없이 계속 작동합니다.DataPower API Gateway 에 대한 새 API를 작성하는 경우에도 메시지 컨텍스트를 작성하는 것이 선호되는 옵션입니다. 이는 API 컨텍스트를 다양한 기본 DataPower API Gateway 정책이 처리하는 방식과 가장 밀접하게 맞추기 때문입니다.
- XSLT 예제
- 헤더를 삭제합니다.
<apigw:clear-header message="'message'" name="'X-My-Header'"/>헤더를 읽습니다.<xsl:variable name="reqType" select="apigw:get-header('request', 'Content-Type')"/> <xsl:variable name="currType" select="apigw:get-header('message', 'Content-Type')"/>헤더를 설정합니다.<apigw:set-header name="'Content-Type'" value="'text/xml'"/>모든 헤더를 가져옵니다.<xsl:variable name="allReqHdrs" select="apigw:all-headers('request')"/> <xsl:variable name="allCurrHdrs" select="apigw:all-headers('message')"/>
메시지 상태 조작 - 예제
message 오브젝트에만 request 오브젝트가 아닌 상태 특성이 있습니다.- GatewayScript 예제
- 상태 코드 및 이유 문구를 읽습니다.
var code = context.message.statusCode; var reason = context.message.reasonPhrase;상태 코드를 업데이트합니다.context.message.statusCode = 400; //integer, update the code, with default reason단일 오퍼레이션으로 상태 코드 및 이유 문구를 업데이트합니다.context.message.statusCode = '200 Wonderful'; //string, update code along with customized reason참고:context.message.reasonPhrase컨텍스트 변수는 읽기 전용입니다. - XSLT 예제
- 상태 코드 및 이유 문구를 읽습니다.
<xsl:variable name="code" select="apigw:get-variable('message.status.code')"/> <xsl:variable name="reason" select="apigw:get-variable('message.status.reason')"/><apigw:set-variable name="'message.status.code'" value="200"/> <apigw:set-variable name="'message.status.reason'" value="'OK'"/>
메시지 본문 액세스
- GatewayScript 예제
- 요청 본문을 읽습니다.
context.request.body.readAsJSON(function(error, json) {}); context.request.body.readAsXML(function(error, xml) {}); context.request.body.readAsBuffer(function(error, buffer) {});메시지 본문을 읽습니다.context.message.body.readAsJSON(function(error, json) {}); context.message.body.readAsXML(function(error, xml) {}); context.message.body.readAsBuffer(function(error, buffer) {});메시지 본문을 쓰고 컨텐츠 유형을 적절히 업데이트합니다.// text response context.message.body.write("Hello world."); context.message.header.set('Content-Type', "text/plain"); // JSON response var pet = { "kind": "dog", "age": 3, "color": "black" }; context.message.body.write(pet); context.message.header.set('Content-Type', "application/json"); // XML response var resp = "<order><id>100</id><timestamp>20181231</timestamp><status>fulfilled</status></order>"; context.message.body.write(resp); context.message.header.set('Content-Type', "text/xml"); - XSLT 예제
- 참고:
- 메시지 본문을 기록할 XSLT API가 없습니다. 스타일시트 변환의 출력이
message.body를 업데이트하는 데 사용됩니다. - 요청 본문이나 메시지 본문을 읽으려면, XSLT 정책이 실행되기 전에 Parse 정책을 사용하여 구문 분석을
message.body수행해야 합니다. 어셈블리 플로우 시작 시message.body는request.body를 포함하므로message.body구문 분석 후에message.body의 요청을 읽을 수 있습니다. - XSLT 입력 문서가 ‘current payload’ 컨텍스트를 사용하는 경우, 해당 입력
'/'문서에는 XSLTmessage.body정책에서 액세스할 수 있는 데이터가 사용되며, 이는 해당 문서가 사전에message.bodyXML로 파싱된 경우에 해당합니다. 이는 XSLT 정책의 ‘property’input속성에 의해 결정되며, 자세한 내용은 xslt를 참조하십시오.
- 메시지 본문을 기록할 XSLT API가 없습니다. 스타일시트 변환의 출력이
세션 거부
- GatewayScript 예
- 오류 이름 및 메시지와 함께 세션을 거부하고 상태 이유 및 코드를 업데이트합니다.
context.reject('CustomError', 'You are not authorized to make this API call'); context.message.statusCode = '401 Unauthorized'; - XSLT 예
- 오류 이름 및 메시지와 함께 세션을 거부하고 상태 이유 및 코드를 업데이트합니다.
<apigw:reject identifier="'CustomError'" status-code="401" reason="'Unauthorized'">You are not authorized to make this API call</apigw:reject>