구현 코드 예

XSLT 및 GatewayScript 코드 스니펫의 예입니다.

참고: GatewayScript, 를 사용하는 경우, 게이트웨이 유형에 따라 다음 명령어 중 하나를 반드시 포함해야 합니다:
DataPower
Gatewayvar apic = require(./apim.custom.js);
DataPower API
Gatewayvar apic = require('apim');
여기서 apic는 이 주제의 GatewayScript 예제에 사용되는 명령 이름입니다. 그러나 apic는 선택사항의 지정된 이름일 수 있습니다. 예를 들어 다음과 같이 사용할 수 있습니다.
var apim = require(./apim.custom.js);
그런 다음 apim을 사용하여 호출을 시작하십시오.

입력 특성 코드 스니펫 액세스

다음 코드 블록은 XSLT policyProperties() 함수를 사용하여 입력 특성에 액세스하는 방법의 예를 표시합니다. 이 예는 정수 값으로 선언되지만 텍스트로서 XSLT로 검색되는 a_property로 이름 지정된 특성을 정의합니다.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dp="http://www.datapower.com/extensions"
  xmlns:func="http://exslt.org/functions"
  xmlns:apim="http://www.ibm.com/apimanagement"
  xmlns:apigw="http://www.ibm.com/xmlns/datapower/2017/11/apigateway"
  exclude-result-prefixes="dp func apim apigw"
  extension-element-prefixes="dp func apim apigw"> 

  <!-- Contains the APIM functions -->
  DataPower
Gateway<xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->
  DataPower API
Gateway<xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <xsl:template match="/">
    <xsl:variable name="p" select="apim:policyProperties()" />
    <xsl:message>
      The value of my input property is
      <xsl:value-of select="$p/a_property" />
      <apigw:set-variable name="'propfound'" value="'true'"/>
    </xsl:message>
  </xsl:template>

</xsl:stylesheet>
GatewayScript를 사용하는 경우 다음 함수를 호출하십시오.
apic.getPolicyProperty(propertyName)
여기서 propertyName은 액세스할 입력 특성 이름입니다. 입력 특성 이름을 비워 두는 경우 조치에서 모든 입력 특성을 리턴합니다.

런타임 컨텍스트 코드 스니펫 액세스

다음 코드 블록은 XSLT getContext() 함수를 사용하여 런타임 컨텍스트에 액세스하는 방법의 예를 표시합니다.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dp="http://www.datapower.com/extensions"
  xmlns:func="http://exslt.org/functions"
  xmlns:apim="http://www.ibm.com/apimanagement"
  exclude-result-prefixes="dp func apim" 
  extension-element-prefixes="dp func apim">

  <!-- Contains the APIM functions -->
  DataPower
Gateway<xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->
  DataPower API
Gateway<xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <xsl:template match="/">
    <xsl:variable name="client-id" select="apim:getContext('client.app.id')" />
    <xsl:message>
      The calling application is
      <xsl:value-of select="$client-id" />
    </xsl:message>
  </xsl:template>

</xsl:stylesheet>
GatewayScript를 사용하는 경우 다음 함수를 호출하십시오.
apic.getContext(varName)
여기서 varName은 액세스할 컨텍스트 변수 이름입니다.

컨텍스트 변수의 전체 목록은 API Gateway context variables를 참조하십시오. 를 사용 중인 경우, DataPower API Gateway 에서 DataPower® API Gateway ‘ GatewayScript 및 XSLT 정책에서 컨텍스트 변수 사용하기’ 항목도 참조하십시오.

입력 페이로드 코드 스니펫에 액세스

다음 코드 블록은 XSLT payloadRead() 함수를 사용하여 입력 페이로드에 액세스하는 방법의 예를 표시합니다.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dp="http://www.datapower.com/extensions"
  xmlns:func="http://exslt.org/functions"
  xmlns:apim="http://www.ibm.com/apimanagement" 
  exclude-result-prefixes="dp func apim"
  extension-element-prefixes="dp func apim">

  <!-- Contains the APIM functions -->
  DataPower
Gateway<xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->
  DataPower API
Gateway<xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <xsl:template match="/">
    <xsl:variable name="input" select="apim:payloadRead()" />
    <xsl:message>
      The input payload is
      <xsl:copy-of select="$input" />
    </xsl:message>
  </xsl:template>

</xsl:stylesheet>
GatewayScript를 사용하는 경우 다음 함수를 호출하십시오.
apic.readInput(callback)
실제 페이로드 읽기는 비동기이므로 콜백이 필요합니다. 페이로드가 준비되면 콜백 메소드가 호출됩니다.
이 함수는 요청의 페이로드를 포함하는 XML 노드 세트를 리턴합니다. 페이로드가 JSON 형식인 경우 XSLT 또는 GatewayScript 스타일시트 내에서 조작할 수 있는 JSONx 노드 세트가 리턴됩니다. 페이로드가 JSON 또는 XML 형식이 아니면 리턴되는 노드 세트는 비어 있습니다.
다음 예는 payloadType() 함수를 사용하여 XSLT payloadRead() 함수에 의해 리턴되는 페이로드 유형(XML 또는 JSONx)을 판별하는 방법을 표시합니다.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dp="http://www.datapower.com/extensions"
  xmlns:func="http://exslt.org/functions"
  xmlns:apim="http://www.ibm.com/apimanagement"
  exclude-result-prefixes="dp func apim" 
  extension-element-prefixes="dp func apim">

  <!-- Contains the APIM functions -->
  DataPower
Gateway<xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->
  DataPower API
Gateway<xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <xsl:template match="/">
    <xsl:variable name="payloadType" select="apim:payloadType()" />
    <xsl:message>
      <xsl:text>Payload type is [</xsl:text>
      <xsl:value-of select="$payloadType" />
      <xsl:text>]</xsl:text>
    </xsl:message>
  </xsl:template>

</xsl:stylesheet>

HTTP 헤더 코드 스니펫 액세스

다음 코드 블록은 getContext() 함수를 사용하여 XSLT로 된 HTTP 헤더에 액세스하는 방법의 예를 표시합니다.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dp="http://www.datapower.com/extensions"
  xmlns:func="http://exslt.org/functions"
  xmlns:apim="http://www.ibm.com/apimanagement" 
  exclude-result-prefixes="dp func apim"
  extension-element-prefixes="dp func apim">

  <!-- Contains the APIM functions -->
  DataPower
Gateway<xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->
  DataPower API
Gateway<xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <xsl:template match="/">
    <xsl:variable name="content-type" select="apim:getContext('request.headers.content-type')" />
    <xsl:message>
      The request content type is
      <xsl:value-of select="$content-type" />
    </xsl:message>
  </xsl:template>

</xsl:stylesheet>
GatewayScript를 사용하는 경우 다음 함수를 호출하십시오.
apic.getContext(request.headers.headerName)
여기서 headerName은 액세스할 헤더 이름에 맵핑됩니다.
참고: ` DataPower ` 확장자(예: dp:set-request-header `.xaml`)를 사용하여 ` HTTP ` 헤더에 접근하거나 수정하는 것은 권장되지 않습니다. 이러한 작업은 해당 정책이 다른 정책이나 어셈블리 단계와 결합될 때 예상치 못한 결과를 초래할 수 있기 때문입니다.

페이로드 코드 스니펫 수정

사용자 정의 정책 의 출력은 XML 또는 SOAP 메시지를 나타내는 XML 노드 세트이거나 JSONx를 사용하는 JSON 메시지여야 합니다. 다음 코드 블록은 XSLT로 된 페이로드를 수정하는 방법의 예를 표시합니다. API 게이트웨이 정책 프레임워크가 새 메시지 또는 변환된 메시지를 승인하도록 지원하려면 다음 예제에 표시된 대로 apim-output 템플리트를 호출하십시오.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:apim="http://www.ibm.com/apimanagement"
  xmlns:jsonx="http://www.ibm.com/xmlns/prod/2009/jsonx"
  exclude-result-prefixes="apim"
  extension-element-prefixes="apim">

  <!-- Contains the APIM functions -->
  DataPower
Gateway<xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->
  DataPower API
Gateway<xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <xsl:template match="/">
    <!-- Creates a JSON document (empty object is for simplicity) -->
    <jsonx:object>
    </jsonx:object>

    <!-- Indicates the media type of the output being produced -->

    <xsl:call-template name="apim:output">
      <xsl:with-param name="mediaType" select="'application/json'" />
    </xsl:call-template>
  </xsl:template>

</xsl:stylesheet>
여기서 mediaType은(는) 다음과 같습니다.
  • 'application/json'은 출력이 JSONx 형식으로 작성되는 경우입니다.
  • 'application/xml'은 출력이 XML 형식으로 작성되는 경우입니다.
GatewayScript를 사용하는 경우 다음 함수를 호출하십시오.
apic.output(mediaType)
여기서 mediaType은(는) 다음과 같습니다.
  • application/json은 출력이 JSONx 형식으로 작성되는 경우입니다.
  • application/xml은 출력이 XML 형식으로 작성되는 경우입니다.

매체 유형을 지정하면 어셈블리 플로우의 다음 단계에서 새 페이로드를 처리하는 방법을 이해할 수 있습니다.

팁: 사용자 정의 정책 의 출력은 XML 또는 JSONx여야 합니다. JSONx는 JSON을 XML로 표시하기 위한 IBM 표준 형식입니다. 출력 GatewayScript JSON 데이터를 JSONx로 변환하는 한 방법은 동일한 정책 규칙 내에서 GatewayScript 조치를 따르도록 Convert Query Params to XML 조치를 추가하는 것입니다. Convert Query Params to XML 조치에는 Default EncodingJSON로 설정된 Input Conversion 가 있어야 합니다. GatewayScript 조치의 출력은 생성될 JSONx에 대한 Convert Query Params to XML 조치의 입력이어야 합니다.

오류 정보 코드 스니펫 구성

다음 XSLT 코드 블록은 apim-error 템플리트를 호출하여 오류 정보를 생성하는 정책 구현을 구성하는 방법의 예를 표시합니다.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:apim="http://www.ibm.com/apimanagement"
  exclude-result-prefixes="apim"
  extension-element-prefixes="apim">

  <!-- Contains the APIM functions -->
  DataPower
Gateway<xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->
  DataPower API
Gateway<xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <!-- Indicates this policy has a failure and provides
       additional information for the client application -->
  <xsl:template match="/">
    <xsl:call-template name="apim:error">
      <xsl:with-param name="httpCode" select="'401'" />
      <xsl:with-param name="httpReasonPhrase" select="'Unauthorized'" />
      <xsl:with-param name="errorMessage" select="'Please select a Plan'" />
    </xsl:call-template>
  </xsl:template>

</xsl:stylesheet>
상황:
  • httpCode는 필수 오류 메시지의 코드입니다.
  • httpReasonPhrase는 오류의 이유입니다.
  • errorMessage는 사용자에게 제안하는 조치입니다.
GatewayScript를 사용하는 경우 다음 함수를 호출하십시오.
apic.error(name, httpCode, httpReasonPhrase, message)
상황:
  • name 은 오류의 이름입니다.
  • httpCode는 필수 오류 메시지의 코드입니다.
  • httpReasonPhrase는 오류의 이유입니다.
  • message는 사용자에게 제안하는 조치입니다.

catch 블록에서 발생한 예외에 액세스

다음 XSLT 코드 블록에서는 API 어셈블리의 catch 블록에서 현재 발생한 예외의 세부사항을 확보할 수 있는 방법에 대한 예제를 보여줍니다. 가능한 사용법은, 발생한 예외의 세부사항을 사용하여 사용자 정의 오류 응답을 작성하는 것입니다.

DataPower Gateway 용 ( v5 호환):
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:dp="http://www.datapower.com/extensions" 
  xmlns:apim="http://www.ibm.com/apimanagement" 
  extension-element-prefixes="dp" 
  exclude-result-prefixes="dp apim">

  <xsl:output method="xml" />

  <!-- Contains the APIM functions -->
  <xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->

  <xsl:template match="/">

    <xsl:variable name="exception" select="apim:getError()"/>
    <!-- output desired error message based on the exception -->
    <myError>
       <errorReason><xsl:value-of select="$exception/error/message"/></errorReason>
    </myError>

    <!-- Propagate the HTTP status code and reason phrase from the exception -->       
    <xsl:call-template name="apim:setVariable">
      <xsl:with-param name="varName" select="'message.status.code'"/>
      <xsl:with-param name="value" select="$exception/error/status/code"/>
      <xsl:with-param name="action" select="'Set'" />
    </xsl:call-template>
              
    <xsl:call-template name="apim:setVariable">
      <xsl:with-param name="varName" select="'message.status.reason'"/>
      <xsl:with-param name="value" select="$exception/error/status/reason"/>
      <xsl:with-param name="action" select="'Set'" />
    </xsl:call-template>
       
    </xsl:template>

</xsl:stylesheet>
API Gateway 용:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:dp="http://www.datapower.com/extensions"
  xmlns:apim="http://www.ibm.com/apimanagement"
  xmlns:apigw="http://www.ibm.com/xmlns/datapower/2017/11/apigateway" 
  extension-element-prefixes="dp apim apigw" 
  exclude-result-prefixes="dp apim apigw">

  <xsl:output method="xml" />

  <!-- Contains the APIM functions -->
  <xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <xsl:template match="/">

    <xsl:variable name="exception" select="apigw:get-error()"/>
    <!-- output desired error message based on the exception -->
    <myError>
       <errorReason><xsl:value-of select="$exception/error/message"/></errorReason>
    </myError>

    <!-- Propagate the HTTP status code and reason phrase from the exception -->       
    <xsl:call-template name="apim:setVariable">
      <xsl:with-param name="varName" select="'message.status.code'"/>
      <xsl:with-param name="value" select="$exception/error/status/code"/>
      <xsl:with-param name="action" select="'Set'" />
    </xsl:call-template>
              
    <xsl:call-template name="apim:setVariable">
      <xsl:with-param name="varName" select="'message.status.reason'"/>
      <xsl:with-param name="value" select="$exception/error/status/reason"/>
      <xsl:with-param name="action" select="'Set'" />
    </xsl:call-template>
       
    </xsl:template>

</xsl:stylesheet>
apim:getError()apigw:get-error() 함수는 XML 노드 세트를 리턴합니다. 예를 들어, 다음과 같습니다.
<?xml version="1.0" encoding="UTF-8"?>
<error>
    <name>RuntimeError</name>
    <message>This is a thrown Runtime Error</message>
    <policyTitle>Throw Runtime Error</policyTitle>
    <status>
        <code>500</code>
        <reason>Internal Server Error</reason>
    </status>
</error>
GatewayScript를 사용하는 경우 다음 함수를 호출하십시오.
apim.getError()
여기서, JSON 오브젝트를 리턴합니다. 예를 들어, 다음과 같습니다.
{
  "name": "OperationError",
  "message": "This is a thrown Operation Error",
  "policyTitle": "Throw Operation Error",
  "status": {
    "code": "500",
    "reason": "Internal Server Error"
  }
}

변수 코드 스니펫 설정

다음 XSLT 코드 블록은 setVariable 템플리트를 호출하여 런타임 변수를 지정된 문자열 값으로 설정하는 방법의 예를 표시합니다.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dp="http://www.datapower.com/extensions"
  xmlns:func="http://exslt.org/functions"
  xmlns:apim="http://www.ibm.com/apimanagement" 
  exclude-result-prefixes="dp func apim"
  extension-element-prefixes="dp func apim">

  <!-- Contains the APIM functions -->
  DataPower
Gateway<xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->
  DataPower API
Gateway<xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <xsl:template match="/">
    <xsl:variable name="" select="'https://endpoint.host.com/data'" />
    <xsl:call-template name="apim:setVariable">
      <xsl:with-param name="varName" select="'serviceEndpoint'" />
      <xsl:with-param name="value" select="$targetUrl" />
      <xsl:with-param name="action" select="'set'" />
    </xsl:call-template>
    <xsl:message>
      <xsl:text>Variable [</xsl:text>
      <xsl:value-of select="'serviceEndpoint'" />
      <xsl:text>] = [</xsl:text>
      <xsl:value-of select="$targetUrl" />
      <xsl:text>]</xsl:text>
    </xsl:message>
    <dp:url-open target="{$targetUrl}" response="xml" http-method="get"/>
    </xsl:message>
  </xsl:template>

</xsl:stylesheet>
상황:
  • varName은 값을 설정할 런타임 변수의 이름입니다.
  • value는 변수를 설정할 문자열 값입니다. 이 값은 리터럴 값 또는 다른 변수일 수 있습니다. 예를 들어, 이름 지정된 변수를 요청에서 Content-Type 헤더의 값으로 설정하려면 value$(request.headers.content-type)으로 지정합니다.
GatewayScript를 사용하는 경우 다음 함수를 호출하십시오.
apic.setvariable(varName, varValue, action)
상황:
  • varName은 값을 설정하거나 추가 또는 지우기를 수행하려는 런타임 변수 이름입니다.
  • varValue는 변수를 설정할 문자열 값입니다. 이 값은 리터럴 값 또는 다른 변수일 수 있습니다. 예를 들어, 이름 지정된 변수를 요청에서 Content-Type 헤더의 값으로 설정하려면 varValuerequest.headers.content-type으로 지정합니다. 이 특성은 set 또는 add가 조치로 지정된 경우에만 필수입니다.
  • action은 변수를 적용할 조치입니다. 유효한 옵션은 다음과 같습니다.
    • set
    • add
    • clear
    옵션을 설정하지 않으면 set의 기본 옵션을 적용합니다.
다음 XSLT 예는 getVariable() 함수를 사용하여 런타임 변수 값을 검색하는 방법을 표시합니다.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dp="http://www.datapower.com/extensions"
  xmlns:func="http://exslt.org/functions"
  xmlns:apim="http://www.ibm.com/apimanagement" 
  exclude-result-prefixes="dp func apim"
  extension-element-prefixes="dp func apim">

  <!-- Contains the APIM functions -->
  DataPower
Gateway<xsl:import href="local:///isp/policy/apim.custom.xsl" /> <!-- Use this import for XSLT 1.0.0 only (v5c Gateway) -->
  DataPower API
Gateway<xsl:include href="store:///dp/apim.custom.xsl" /> <!-- Use this include for XSLT 2.0.0 only (API Gateway) -->

  <xsl:template match="/">
    <xsl:variable name="varValue" select="apim:getVariable('serviceEndpoint')" />
    <xsl:message>
      <xsl:text>Variable [</xsl:text>
      <xsl:value-of select="'serviceEndpoint'" />
      <xsl:text>] = [</xsl:text>
      <xsl:value-of select="$varValue" />
      <xsl:text>]</xsl:text>
    </xsl:message>
    <dp:url-open target="{$varValue}" response="xml" http-method="get"/>
  </xsl:template>

</xsl:stylesheet>
여기서,
  • varValue는 값을 검색할 런타임 변수의 이름입니다.
GatewayScript를 사용하는 경우 다음 함수를 호출하십시오.
apic.getvariable(varName)
여기서 varName은 값을 검색할 런타임 변수의 이름입니다.