Docs Menu
Docs Home
/ /
Atlas App Services
/

Context

項目一覧

  • Overview
  • アプリ メタデータを取得する( context.app
  • 関数の呼び出し( context.functions
  • アプリ環境を確認します( context.environment
  • context.environment.values
  • MongoDB データソースまたはサードパーティ サービスに接続する( context.services
  • リクエスト メタデータを取得する( context.request
  • ユーザー データを取得する( context.user
  • 値を参照する( context.values
  • HTTP リクエストの送信( context.http

Atlas Functionは、受信リクエストのメタデータを含むグローバル contextオブジェクトにアクセスし、App Services App で構成したコンポーネントとサービスにアクセスできます。

contextオブジェクトは次のインターフェースを公開します。

プロパティ
説明
context.app
関数を実行しているアプリに関するメタデータにアクセスします。
環境値と現在の環境タグにアクセスします。
組み込み HTTP クライアント。
関数呼び出しをトリガーした受信リクエストについて説明します。
リクエストを開始した認証済みユーザーについて説明します。
静的グローバル値が含まれます。

context.appオブジェクトには、関数を含むアプリに関するメタデータが含まれています。

{
"id": string,
"clientAppId": string,
"name": string,
"projectId": string,
"deployment": {
"model": string,
"providerRegion": string,
},
"lastDeployed": string,
"hostingUri": string,
}
context.app.id

関数を含むアプリの一意の内部 ID。

"60c8e59866b0c33d14ee634a"
context.app.clientAppId

関数を含むアプリの一意のクライアントアプリ ID。

"myapp-abcde"
context.app.name

関数を含むアプリの名前。

"myapp"
context.app.projectId

アプリを含む Atlas プロジェクトの ID。

"5e1ec444970199272441a214"
context.app.deployment

アプリの配置モデルとリージョンを記述するオブジェクト。

{
"model": "LOCAL",
"providerRegion": "aws-us-east-1"
}
context.app.lastDeployed

Atlas アプリが最後に配置された日付と時刻( ISODate string として形式)。

"2022-10-31T12:00:00.000Z"
context.app.hostingUri

静的ホスティングが有効になっている場合、この値はホストされたアセットのベース URL になります。 (静的ホスティングは非推奨です。 詳細はこちら )。

"myapp-abcde.mongodbstitch.com"

context.functionsインターフェースを介して、アプリケーション内の任意の関数を呼び出すことができます。

context.functions.execute()

特定の関数を呼び出し、その結果を返します。

context.functions.execute(functionName, ...args)
Parameter
タイプ
説明
functionName
string
関数の名前。
args...
混合
関数に渡す引数の可変長リスト。 各関数パラメーターは、個別のカンマ区切りの引数にマップされます。

// difference: subtracts b from a using the sum function
exports = function(a, b) {
return context.functions.execute("sum", a, -1 * b);
};

アプリの現在の環境構成に関する情報と環境固有の値には、 context.environmentインターフェースからアクセスできます。

context.environment.tag

アプリの現在の環境の名前を string として表します。

Possible values:

  • ""

  • "development"

  • "testing"

  • "qa"

  • "production"

exports = async function() {
switch(context.environment.tag) {
case "": {
return "There is no current environment"
}
case "development": {
return "The current environment is development"
}
case "testing": {
return "The current environment is testing"
}
case "qa": {
return "The current environment is qa"
}
case "production": {
return "The current environment is production"
}
}
};

各フィールドが環境値の名前を現在の環境内の値にマッピングするオブジェクト。

exports = async function() {
const baseUrl = context.environment.values.baseUrl
};

リンクされた MongoDB Atlas クラスターまたはフェデレーティッド データソースのクライアントには、 context.servicesインターフェースからアクセスできます。 サードパーティのサービスにアクセスすることもできますが、この機能は非推奨です。

context.services.get()

指定されたサービスのサービス クライアントを取得します。そのようなサービスが存在しない場合はundefinedを取得します。

context.services.get(serviceName)
Parameter
タイプ
説明
serviceName
string

リンクされたクラスター、フェデレーティッドデータベースインスタンス、またはサービスの名前。

Tip

MongoDB サービス名

アプリによって作成されたリンクされたデータソースでは、次のいずれかのデフォルト名が使用されます。

  • クラスター: mongodb-atlas

  • フェデレーティッドデータベースインスタンス: mongodb-datafederation

MongoDB Atlas でのデータの読み取りと書込み
exports = async function() {
// Get the cluster's data source client
const mdb = context.services.get("mongodb-atlas");
// Reference a specific database/collection
const db = mdb.db("myApp");
const collection = db.collection("myCollection");
// Run a MongoDB query
return await collection.find({
name: "Rupert",
age: { $lt: 50 },
})
};
[非推奨] サードパーティのサービスアクションを呼び出す
exports = async function() {
// Instantiate a service client for the HTTP Service named "myHttpService"
const http = context.services.get("myHttpService");
// Call the HTTP service's get() action
try {
const response = await http.get({ url: "https://www.mongodb.com" });
return response.body.text()
} catch(err) {
// You might get an error if:
// - you passed invalid arguments
// - the service's rules prevent the action
console.error(err)
}
};

context.requestインターフェイスを使用して、受信リクエストに関する情報にアクセスできます。

Tip

context.requestインターフェースにはリクエスト本体のペイロードは含まれていません。 HTTPS endpoints 関数では、提供されたrequest引数からリクエスト本文やその他のリクエストの詳細にアクセスできます。

context.request

関数の実行の原因となった HTTP リクエストに関する情報を含むオブジェクト。

{
"remoteIPAddress": <string>,
"requestHeaders": <object>,
"webhookUrl": <string>,
"httpMethod": <string>,
"rawQueryString": <string>,
"httpReferrer": <string>,
"httpUserAgent": <string>,
"service": <string>,
"action": <string>
}
フィールド
タイプ
説明
remoteIPAddress
string
関数リクエストを発行したクライアントの IP アドレス。
requestHeaders
オブジェクト

各フィールドが HTTP ヘッダー のタイプにマップされるオブジェクト 関数を実行する原因となったリクエストに含まれていた。各フィールドの値は文字列の配列であり、各stringはリクエストに含まれた指定された型のヘッダーにマップされます。

{
"requestHeaders": {
"Content-Type": ["application/json"],
"Cookie": [
"someCookie=someValue",
"anotherCookie=anotherValue"
]
}
}
webhookUrl
string
任意。 HTTPS endpoints関数では、エンドポイントのルートです。
httpMethod
string
任意。 HTTPS endpoints 関数では、 HTTP メソッド エンドポイントを呼び出したリクエストの
rawQueryString
string

クエリstring 受信HTTP リクエストに添付されます。すべてのクエリ パラメーターは、指定されたのと同じ順序で表示されます。

重要

App Services はシークレット パラメーターを削除します

セキュリティ上の理由から、 Atlas App Servicesは、キーが secret であるクエリstringのキーと値のペアを自動的に削除します。 たとえば、受信リクエストのクエリstringが ?secret=hello&someParam=42 の場合、そのリクエストの rawQueryString"someParam=42" になります。

httpReferrer
string

任意。 リクエストが送信されたページの URL 。

この値は、 HTTP reference ヘッダー から派生します 。リクエストにRefererヘッダーが含まれていない場合、これはundefinedになります。

httpUserAgent
string

任意。 ソフトウェア ベンダー、オペレーティング システム、アプリケーションの種類など、リクエストのソースを識別する特性情報。

この値は、 HTTP ユーザーエージェント ヘッダー から派生します 。リクエストにUser-Agentヘッダーが含まれていない場合、これはundefinedになります。

次のcontext.requestドキュメントは、macOS Advanced Sierra で Chrome 73 を使用して参照するユーザーによって、 https://myapp.example.com/から発行された関数呼び出しを反映しています。

exports = function() {
return context.request
}
{
"remoteIPAddress": "54.173.82.137",
"httpReferrer": "https://myapp.example.com/",
"httpUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",
"rawQueryString": "?someParam=foo&anotherParam=42",
"requestHeaders": {
"Content-Type": ["application/json"],
"Cookie": [
"someCookie=someValue",
"anotherCookie=anotherValue"
]
}
}

context.userインターフェースを使用して、関数を呼び出したアプリケーションまたはシステムユーザーに関する情報にアクセスできます。

context.user

関数を呼び出した認証ユーザーのユーザー オブジェクト

{
"id": <string>,
"type": <string>,
"data": <document>,
"identities": <array>
}
フィールド
タイプ
説明
id
string
ユーザーを一意に識別するObjectIdの string 表現。
type
string

ユーザーのタイプ。 次のタイプが利用可能です。

タイプ
説明
" Normal"
ユーザーは、 API キー プロバイダー以外の認証プロバイダーを介してログインする アプリケーション ユーザー です。
"server"
"system"
ユーザーは 、すべてのルールをバイパスするシステムユーザーです。
data
ドキュメント

ユーザーを説明するメタデータを含むドキュメント。 このフィールドは、ユーザーに関連付けられているすべてのidentitiesのデータを組み合わせたものであるため、正確なフィールド名と値は、ユーザーが認証された認証プロバイダによって異なります。

注意

システム関数にはユーザー データはありません

システム関数では、 user.dataオブジェクトは空です。 関数がシステムユーザーとして実行されているかどうかをテストするには、 context.runningAsSystem()を使用します。

custom_data
ドキュメント

アプリケーションのカスタム ユーザー データ コレクションからのドキュメントで、ユーザーの ID を指定します。 カスタム ユーザー データ コレクションを使用して、アプリケーションのユーザーに関する任意のデータを保存できます。 nameフィールドを設定すると、App Services はusernameメタデータ フィールドにnameの戻り値を入力します。 Atlas App Services は、ユーザーがログインする際などアクセス トークンを更新するたびに、データの新しいコピーを自動的に取得します。 基礎となるデータは通常の MongoDB ドキュメントであるため、 MongoDB Atlas サービスを通じて標準の CRUD 操作を使用して、ユーザーのカスタム データの定義および変更を行うことができます。

注意

大規模なカスタム ユーザー データの保存を避ける

カスタム ユーザー データは、MongoDB ドキュメントの最大サイズである16MBに制限されています。 この制限に達しないようにするには、ユーザーの希望言語やアトミックイメージの URL など、小規模で比較的静的なユーザー データを各カスタム ユーザー データ ドキュメントに保存することを検討してください。 大規模なデータ、境界のないデータ、または頻繁に更新されるデータの場合は、カスタム ユーザー ドキュメントにデータへの参照のみを保存するか、カスタム ユーザー ドキュメントではなくユーザーの ID を参照してデータを保存することを検討してください。

identities
配列

ユーザーに関連付けられた認証プロバイダ ID のリスト。 ユーザーが初めて特定のプロバイダーにログインすると、App Services はそのユーザーを、一意な識別子とプロバイダーからのユーザーに関する追加メタデータを含む ID オブジェクトに関連付けます。 後続のログインでは、App Services は既存の ID データを更新しますが、新しい ID は作成しません。 ID オブジェクトの形式は次のとおりです。

{
"id": "<Unique ID>",
"provider_type": "<Provider Name>",
"data": {
"<Metadata Field>": <Value>,
...
}
}
フィールド名
説明
id
この ID を一意に識別するプロバイダーが生成したstring
provider_type
この ID に関連付けられている認証プロバイダのタイプ。
data
ユーザーを説明する認証プロバイダーからの追加メタデータ。 具体的なフィールド名と値は、ユーザーがログインした認証プロバイダによって異なります。 ユーザー ID データのプロバイダー固有の内訳については、「ユーザー メタデータ 」を参照してください。

次のcontext.user ドキュメントは、単一の ユーザー API キー に関連付けられている メール/パスワード ユーザーを反映しています。

exports = function() {
return context.user
}
{
"id": "5cbf68583025b12840664682",
"type": "normal",
"data": {
"email": "someone@example.com",
"name": "myApiKeyName"
},
"identities": [
{
"id": "5cbf68583025b12880667681",
"provider_type": "local-userpass"
},
{
"id": "5cbf6c6a922616045a388c71",
"provider_type": "api-key"
}
]
}
context.runningAsSystem()

関数がシステムユーザーとして実行されている場合はtrue 、それ以外の場合はfalseとしてブール値として評価されます。

exports = function() {
const isSystemUser = context.runningAsSystem()
if(isSystemUser) {
// Do some work that bypasses rules
} else {
// Do some work in the context of the user that called the function.
}
}

context.valuesインターフェースを使用して、関数内のアプリの静的にアクセスできます。

context.values.get(valueName)

指定された値名に関連付けられているデータを取得します。または、そのような値が存在しない場合はundefinedを取得します。 このデータは、プレーンテキストの JSON 値であるか、値を通じて公開されるシークレットのいずれかです。

Parameter
タイプ
説明
valueName
string

exports = function() {
// Get a global value (or `undefined` if no value has the specified name)
const theme = context.values.get("theme");
console.log(theme.colors) // Output: { red: "#ee1111", blue: "#1111ee" }
console.log(theme.colors.red) // Output: "#ee1111"
};

context.http インターフェースを使用して組み込みクライアントを介してHTTPS requestsを送信できます。

context.http.get()

HTTP GET を送信する 指定された URL に対するリクエストを送信します。パラメータの定義や戻り値の型などの詳細な参照情報については、 http.get()を参照してください。

exports = async function() {
const response = await context.http.get({ url: "https://www.example.com/users" })
// The response body is a BSON.Binary object. Parse it and return.
return EJSON.parse(response.body.text());
};
context.http.post()

HTTP POST を送信する 指定された URL に対するリクエストを送信します。パラメータの定義や戻り値の型などの詳細な参照情報については、 http.post()を参照してください。

exports = async function() {
const response = await context.http.post({
url: "https://www.example.com/messages",
body: { msg: "This is in the body of a POST request!" },
encodeBodyAsJSON: true
})
// The response body is a BSON.Binary object. Parse it and return.
return EJSON.parse(response.body.text());
};
context.http.put()

HTTP PUT を送信する 指定された URL に対するリクエストを送信します。パラメータの定義や戻り値の型などの詳細な参照情報については、 http.put()を参照してください。

exports = async function() {
const response = await context.http.put({
url: "https://www.example.com/messages",
body: { msg: "This is in the body of a PUT request!" },
encodeBodyAsJSON: true
})
// The response body is a BSON.Binary object. Parse it and return.
return EJSON.parse(response.body.text());
};
context.http.patch()

HTTP PATCH の送信 指定された URL に対するリクエストを送信します。パラメータの定義や戻り値の型などの詳細な参照情報については、 http.patch()を参照してください。

exports = async function() {
const response = await context.http.patch({
url: "https://www.example.com/diff.txt",
body: { msg: "This is in the body of a PATCH request!" },
encodeBodyAsJSON: true
})
// The response body is a BSON.Binary object. Parse it and return.
return EJSON.parse(response.body.text());
};
context.http.delete()

HTTP DELETE の送信 指定された URL に対するリクエストを送信します。パラメータの定義や戻り値の型などの詳細な参照情報については、 http.delete()を参照してください。

exports = async function() {
const response = await context.http.delete({ url: "https://www.example.com/user/8675309" })
};
context.http.head()

HTTP HEAD を送信する 指定された URL に対するリクエストを送信します。パラメータの定義や戻り値の型などの詳細な参照情報については、 http.head()を参照してください。

exports = async function() {
const response = await context.http.head({ url: "https://www.example.com/users" })
// The response body is a BSON.Binary object. Parse it and return.
EJSON.parse(response.body.text());
};

戻る

MongoDB API リファレンス