このページは Apigee と Apigee ハイブリッドに適用されます。
Apigee Edge のドキュメントを表示する。
JavaScript ポリシーを使用すると、API プロキシフローのコンテキストで実行されるカスタム JavaScript コードを追加できます。このポリシーを使用すると、Apigee ポリシーでカバーされていないカスタム動作を実装できます。
カスタム JavaScript コードでは、Apigee JavaScript オブジェクト モデルのオブジェクト、メソッド、プロパティを使用できます。プロキシ フロー コンテキストで変数の取得 / 設定 / 削除、カスタム ロジックの実行、障害処理の実行、リクエストやレスポンスからのデータの抽出、バックエンド ターゲット URL の動的編集を行うことができます。オブジェクト モデルで入手できる基本的な暗号機能を使用することもできます。
JavaScript ポリシーでは、実行する JavaScript ソースファイルを指定できます。また、<Source> 要素を使用して、ポリシーの構成に直接 JavaScript コードを組み込むことができます。いずれの場合も、ポリシーが関連付けられているステップが実行されると、JavaScript コードが実行されます。
ソースファイル オプションでは、ソースコードは常にプロキシ バンドル内の標準の場所(apiproxy/resources/jsc)に格納されます。ソースコードを環境レベルまたは組織レベルのリソース ファイルに保存することもできます。手順については、リソース ファイルをご覧ください。Apigee UI プロキシ エディタを使用して JavaScript をアップロードすることもできます。
Apigee は、次の目的で JavaScript ポリシーを使用することを推奨していません。
- ロギング。MessageLogging ポリシーは、Splunk、Sumo、Loggly などのサードパーティのロギング プラットフォームでのロギングに適しています。このポリシーは、レスポンスがクライアントに返された後に PostClientFlow を実行することで、API プロキシのパフォーマンスも向上させます。
- Apigee ポリシーの置き換え。JavaScript ポリシーは、Apigee ポリシーの機能を置き換えるものではありません。必要な機能が Apigee ポリシーで利用可能な場合は、カスタム JavaScript ソリューションを実装するのではなく、そのポリシーを使用してください。Apigee のポリシーに比べ、カスタム JavaScript コードはパフォーマンスや最適化の面で劣る可能性があります。
JavaScript ソースファイルには .js という拡張子を付ける必要があります。
Apigee では、Rhino JavaScript エンジン 1.7.13 で実行される JavaScript をサポートしています。
このポリシーは拡張可能なポリシーであり、Apigee ライセンスによっては、このポリシーの使用によって費用や使用量に影響する場合があります。ポリシータイプと使用量への影響については、ポリシータイプをご覧ください。
サンプル
ターゲット URL を書き直す
一般的なユースケースでは、リクエスト本文からデータを抽出し、フロー変数に保存して、そのフロー変数をプロキシフローの他の場所で使用します。たとえば、ユーザーが HTML フォームに名前を入力して送信するとします。フォームのデータを抽出してバックエンド サービスの URL に動的に追加するには、JavaScript ポリシーを使用します。
- Apigee UI で、プロキシ エディタで作成したプロキシを開きます。
- [Develop] タブを選択します。
- [New] メニューから [New Script] を選択します。
- ダイアログで JavaScript を選択し、スクリプトに「
js-example」という名前を付けます。 - 次のコードをコードエディタに貼り付けて、プロキシを保存します。
contextオブジェクトは、プロキシフローのどこにあっても JavaScript コードで使用できます。フロー固有の定数を取得したり、便利なget/setメソッドを呼び出したり、その他のオペレーションを実行したりします。このオブジェクトは Apigee JavaScript オブジェクト モデルの一部です。target.urlフロー変数は、ターゲット リクエスト フローでアクセスできる組み込みの読み取り / 書き込み変数です。この変数を API URL に設定すると、Apigee はそのバックエンド URL を呼び出します。これにより、元のターゲット URL(プロキシの作成時に指定した URL、http://www.example.comなど)が書き換えられます。if (context.flow=="PROXY_REQ_FLOW") { var username = context.getVariable("request.formparam.user"); context.setVariable("info.username", username); } if (context.flow=="TARGET_REQ_FLOW") { context.setVariable("request.verb", "GET"); var name = context.getVariable("info.username"); var url = "http://mocktarget.apigee.net/" context.setVariable("target.url", url + "?user=" + name); }
- [New Policy] メニューから [JavaScript] を選択します。
- ポリシー
target-rewriteに名前を付けます。デフォルト値をそのまま使用して、ポリシーを保存します。 - [Navigator] で [Proxy Endpoint Preflow] を選択すると、そのフローにポリシーが追加されます。
- [Navigator] で [Target Endpoint PreFlow] を選択します。
- フローエディタの [Navigator] から、[Target Endpoint] の [Request] 側に JavaScript ポリシーをドラッグします。
- 保存します。
- API を呼び出すときは、組織名とプロキシ名を置き換えます。
curl -i -H 'Content-Type: application/x-www-form-urlencoded' -X POST -d 'user=Will' http://myorg-test.apigee.net/js-example
この例で使用した JavaScript ポリシーの XML 定義を見てみましょう。<ResourceURL> 要素は、実行する JavaScript ソースファイルを指定します。このパターンは、すべての JavaScript ソースファイル(jsc://filename.js)に適用されます。JavaScript コードでインクルードが必要な場合は、このドキュメントで後述するように、1 つ以上の <IncludeURL> 要素を使用します。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" name="target-rewrite"> <DisplayName>target-rewrite</DisplayName> <Properties/> <ResourceURL>jsc://js-example.js</ResourceURL> </Javascript>
JavaScript からプロパティ値を取得する
構成に <Property> 要素を追加して、実行時にその値を JavaScript で取得できます。
要素の name 属性を使用して、JavaScript コードからプロパティにアクセスするための名前を指定します。<Property> 要素の値(開始タグと終了タグの間の値)は、JavaScript が受け取るリテラル値です。
JavaScript では、次のように Properties オブジェクトのプロパティとしてアクセスし、ポリシーのプロパティ値を取得します。
- プロパティを構成します。プロパティ値は変数名
response.status.codeです。<Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" name="JavascriptURLRewrite"> <DisplayName>JavascriptURLRewrite</DisplayName> <Properties> <Property name="source">response.status.code</Property> </Properties> <ResourceURL>jsc://JavascriptURLRewrite.js</ResourceURL> </Javascript>
- JavaScript を使用してプロパティを取得します。
getVariable関数は、取得した変数名を使用して変数の値を取得します。var responseCode = properties.source; // Returns "response.status.code" var value = context.getVariable(responseCode); // Get the value of response.status.code context.setVariable("response.header.x-target-response-code", value);
エラー処理
JavaScript コールアウトで使用できるエラー処理手法の例については、JavaScript ポリシーからエラーを返す正しい方法をご覧ください。Apigee コミュニティでの提案は情報提供のみを目的としたものであり、必ずしも Google が推奨するベスト プラクティスではありません。
要素リファレンス
要素リファレンスは、JavaScript ポリシーの要素と属性を記述しています。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" name="JavaScript-1"> <DisplayName>JavaScript 1</DisplayName> <Properties> <Property name="propName">propertyValue</Property> </Properties> <SSLInfo> <Enabled>trueFalse</Enabled> <ClientAuthEnabled>trueFalse</ClientAuthEnabled> <KeyStore>ref://keystoreRef</KeyStore> <KeyAlias>keyAlias</KeyAlias> <TrustStore>ref://truststoreRef</TrustStore> </SSLInfo> <IncludeURL>jsc://a-javascript-library-file</IncludeURL> <ResourceURL>jsc://my-javascript-source-file</ResourceURL> <Source>insert_js_code_here</Source> </Javascript>
<Javascript> 属性
< languageVersion="VERSION_1_3" Javascript name="Javascript-1" enabled="true" continueOnError="false" async="false" timeLimit="200">
| 属性 | 説明 | デフォルト | 要否 |
|---|---|---|---|
| 言語バージョン |
コードが記述されている JavaScript 言語のバージョンを指定します。値は |
VERSION_DEFAULT | オプション |
| timeLimit |
スクリプトを実行できる最大時間(ミリ秒)を指定します。たとえば、200 ミリ秒の上限を超えると、ポリシーはエラー |
なし | 必須 |
The following table describes attributes that are common to all policy parent elements:
| Attribute | Description | Default | Presence |
|---|---|---|---|
name |
The internal name of the policy. The value of the Optionally, use the |
N/A | Required |
continueOnError |
Set to Set to |
false | Optional |
enabled |
Set to Set to |
true | Optional |
async |
This attribute is deprecated. |
false | Deprecated |
<DisplayName> element
Use in addition to the name attribute to label the policy in the
management UI proxy editor with a different, natural-language name.
<DisplayName>Policy Display Name</DisplayName>
| Default |
N/A If you omit this element, the value of the policy's |
|---|---|
| Presence | Optional |
| Type | String |
<IncludeURL> 要素
<ResourceURL> 要素または <Source> 要素で指定されたメインの JavaScript ファイルの依存関係として読み込まれる JavaScript ライブラリ ファイルを指定します。ポリシーは、ポリシーに記述されている順序でスクリプトを評価します。コードでは、JavaScript オブジェクト モデルのオブジェクト、メソッド、プロパティを使用できます。
複数の JavaScript 依存関係リソースを含めるには、追加の <IncludeURL> 要素を使用します。
<IncludeURL>jsc://my-javascript-dependency.js</IncludeURL>
| デフォルト: | なし |
| 要否: | 省略可 |
| 型: | 文字列 |
<Property> 要素
JavaScript コードからランタイム時にアクセスできるプロパティを指定します。
<Properties> <Property name="propName">propertyValue</Property> </Properties>
| デフォルト: | なし |
| 要否: | 省略可 |
| 型: | 文字列 |
属性
| 属性 | 説明 | デフォルト | 要否 |
|---|---|---|---|
| name |
プロパティの名前を指定します。 |
なし | 必須 |
例
サンプル セクションの例をご覧ください。
<ResourceURL> 要素
API フローで実行するメインの JavaScript ファイルを指定します。このファイルは、API プロキシ スコープ(API プロキシ バンドルの /apiproxy/resources/jsc または API プロキシ エディタの [Navigator] ペインの [Scripts] セクション)に保存できます。または、リソースの管理の説明に従って、組織スコープまたは環境スコープに保存して、複数の API プロキシ間で再利用することもできます。コードでは、JavaScript オブジェクト モデルのオブジェクト、メソッド、プロパティを使用できます。
<ResourceURL>jsc://my-javascript.js</ResourceURL>
| デフォルト: | なし |
| 要否: | <ResourceURL> または <Source> が必須。<ResourceURL> と <Source> の両方が存在する場合、ポリシーは <ResourceURL> を無視します。 |
| 型: | 文字列 |
例
サンプル セクションの例をご覧ください。
<Source> 要素
ポリシーの XML 構成に JavaScript を直接挿入できます。挿入された JavaScript コードは、ポリシーが API フローで実行された際に実行されます。
| デフォルト: | なし |
| 要否: | <ResourceURL> または <Source> が必須。<ResourceURL> と <Source> の両方が存在する場合、ポリシーは <ResourceURL> を無視します。 |
| 型: | 文字列 |
例
<Javascript name='JS-ParseJsonHeaderFullString' timeLimit='200' > <Properties> <Property name='inboundHeaderName'>specialheader</Property> <Property name='outboundVariableName'>json_stringified</Property> </Properties> <Source> var varname = 'request.header.' + properties.inboundHeaderName + '.values.string'; var h = context.getVariable(varname); if (h) { h = JSON.parse(h); h.augmented = (new Date()).valueOf(); var v = JSON.stringify(h, null, 2) + '\n'; // further indent var r = new RegExp('^(\S*)','mg'); v= v.replace(r,' $1'); context.setVariable(properties.outboundVariableName, v); } </Source> </Javascript>
<SSLInfo> 要素
JavaScript ポリシーにより作成されたすべての HTTP クライアント インスタンスに TLS を構成するために使用するプロパティを指定します。
<SSLInfo> <Enabled>trueFalse</Enabled> <ClientAuthEnabled>trueFalse</ClientAuthEnabled> <KeyStore>ref://keystoreRef</KeyStore> <KeyAlias>keyAlias</KeyAlias> <TrustStore>ref://truststoreRef</TrustStore> </SSLInfo>
| デフォルト: | なし |
| 要否: | 省略可 |
| 型: | 文字列 |
HTTP クライアントに TLS を構成するプロセスは、TargetEndpoint / TargetServer に TLS を構成するプロセスと同じです。詳細については、TLS の構成オプションをご覧ください。
使用上の注意
JavaScript ポリシーコードのデバッグ
print() 関数を使用して、デバッグ情報を Debug ツールのトランザクション出力パネルに出力します。詳細と例については、print() ステートメントでの JavaScript のデバッグをご覧ください。
Debug ツールで print ステートメントを表示するには:
- Debug ツールを開き、JavaScript ポリシーを含むプロキシのトレース セッションを開始します。
- プロキシを呼び出します。
- Debug ツールで、[Output from all Transactions] をクリックして出力パネルを開きます。
![Apigee Trace ツールの [Output from all Transactions] パネルに、print ステートメントが表示されている。](https://docs.cloud.google.com/static/apigee/docs/api-platform/images/output-transactions.png?authuser=1&hl=ja)
- print ステートメントはこのパネルに表示されます。
フロー変数
このポリシーは、デフォルトでは変数に何も入力しません。ただし、context オブジェクトでメソッドを呼び出すことで、JavaScript コードでフロー変数を設定して取得できます。例:
context.setVariable("response.header.X-Apigee-Target", context.getVariable("target.name"))
context オブジェクトは Apigee JavaScript オブジェクト モデルの一部です。
エラー リファレンス
This section describes the fault codes and error messages that are returned and fault variables that are set by Apigee when this policy triggers an error. This information is important to know if you are developing fault rules to handle faults. To learn more, see What you need to know about policy errors and Handling faults.
Runtime errors
These errors can occur when the policy executes.
| Fault code | HTTP status | Cause | Fix |
|---|---|---|---|
steps.javascript.ScriptExecutionFailed |
500 |
The JavaScript policy can throw many different types of ScriptExecutionFailed errors. Commonly
seen types of errors include
RangeError,
ReferenceError,
SyntaxError,
TypeError, and
URIError. |
build |
steps.javascript.ScriptExecutionFailedLineNumber |
500 |
An error occurred in the JavaScript code. See the fault string for details. |
N/A |
steps.javascript.ScriptSecurityError |
500 |
A security error occurred when the JavaScript executed. See the fault string for
details. |
N/A |
Deployment errors
These errors can occur when you deploy a proxy containing this policy.
| Error name | Cause | Fix |
|---|---|---|
InvalidResourceUrlFormat |
If the format of the resource URL specified within the <ResourceURL> or the <IncludeURL> element of the JavaScript policy is invalid, then the deployment of the API proxy fails. |
build |
InvalidResourceUrlReference |
If the <ResourceURL> or the <IncludeURL> elements
refer to a JavaScript file that does not exist, then the deployment of the API proxy fails.
The referenced source file must exist either the API proxy, environment, or organization level. |
build |
WrongResourceType |
This error occurs during deployment if the <ResourceURL> or the <IncludeURL>
elements of the JavaScript policy refer to any resource type other than jsc (JavaScript file). |
build |
NoResourceURLOrSource |
The deployment of the JavaScript policy can fail with this error if the <ResourceURL>
element is not declared or if the resource URL is not defined within this element.
<ResourceURL> element is a mandatory element. Or, The <IncludeURL> element is declared
but the resource URL is not defined within this element. The <IncludeURL> element is optional
but if declared, the resource URL must be specified within the <IncludeURL> element. |
build |
Fault variables
These variables are set when this policy triggers an error at runtime. For more information, see What you need to know about policy errors.
| Variables | Where | Example |
|---|---|---|
fault.name="fault_name" |
fault_name is the name of the fault, as listed in the Runtime errors table above. The fault name is the last part of the fault code. | fault.name Matches "ScriptExecutionFailed" |
javascript.policy_name.failed |
policy_name is the user-specified name of the policy that threw the fault. | javascript.JavaScript-1.failed = true |
Example error response
{ "fault": { "faultstring": "Execution of SetResponse failed with error: Javascript runtime error: "ReferenceError: "status" is not defined. (setresponse.js:6)\"", "detail": { "errorcode": "steps.javascript.ScriptExecutionFailed" } } }
Example fault rule
<FaultRule name="JavaScript Policy Faults"> <Step> <Name>AM-CustomErrorResponse</Name> <Condition>(fault.name Matches "ScriptExecutionFailed") </Condition> </Step> <Condition>(javascript.JavaScript-1.failed = true) </Condition> </FaultRule>
スキーマ
各ポリシータイプは XML スキーマ(.xsd)によって定義されます。参照用のポリシー スキーマは GitHub から入手できます。
関連トピック
Apigee コミュニティの記事
以下の関連記事は、Apigee コミュニティでご覧いただけます。