機械翻訳について

23 カスタム・コードからAPIを呼び出す

サービス開発者は、カスタム・コードからプラットフォームAPI、コネクタAPI、およびその他のカスタムAPIにアクセスすることができます。 カスタム・コードSDKは、これらのAPIへのリクエストを簡単にするメソッドを提供します。

MCS APIへのリクエストの送信方法

カスタム・コードSDKメソッドを使用して、MCS APIにリクエストを送信します。 これらのメソッドの1つを呼び出すと、このメソッドはMCS APIに対してRESTful HTTPコールを実行します。 このSDKはHTTP呼び出しをほとんど透過的にしますが、メソッド引数とその戻り値はRESTfulなHTTPリクエストとレスポンスで見られるものに似ています。

これらのメソッドとその引数は共通のパターンに従います。 このセクションでは、このパターンについて説明します。以下のセクションでは、APIのメソッドに固有の詳細について説明します:

注意:

注意: この章の例の目的は、カスタム・コード・サービスとのインタフェース方法を説明することです。 これらの例は、Node.js REST API実装を作成するためのベスト・プラクティスを教えることを意図したものではありません。

APIリクエスト・パターン

カスタム、プラットフォーム、およびコネクタAPIへのリクエストを行うカスタム・コードSDKメソッドは、次のパターンに従います:

req.oracleMobile.<service>.<method>(required arguments, options, httpOptions)

<service>は、呼び出すAPIを識別します。

  • プラットフォームAPIの場合は、storageumsnotificationなど、プラットフォームの名前です。

  • コネクタAPIの場合、これはconnectorsまたはconnectors.<api>のいずれかです。 後で、どちらを使用するかを選択する方法について説明します。

  • カスタムAPIの場合は、customまたはcustom.<api>のいずれかになります。 後で、どちらを使用するかを選択する方法について説明します。

オプションのAPI固有のプロパティを指定するには、optionsを使用します。 次のセクションでは、これらのメソッドの多くで共有されるoptionsプロパティについて説明します。 次のセクションの各メソッドの説明は、そのメソッドに適用される追加のoptionsプロパティについて説明します(存在する場合)。

httpOptions引数は、Node.js http.request(options)引数のようなものです。 この引数を使用して、必要な引数とoptionsでカバーされていないプロパティを渡します。 たとえば、timeoutプロパティを渡してリクエストを終了する前にリクエストが応答するのを待機するミリ秒数を指定する必要がある場合は、httpOptionsに渡します。 httpOptionsを使用する別の例は、問合せパラメータをコネクタに渡すことです。 http.request(options)の詳細については、https://github.com/mikeal/requestのAPIドキュメントにアクセスして、request(options, callback)というタイトルのセクションまでスクロールしてください。

ヒント:

httpOptions.qsを使用して問合せ文字列を渡すときは、qs値にencodeURIComponent(<string>) を使用して、コードがマルチバイト文字を処理するようにすることができます。

optionsおよびhttpOptions引数は省略できます。 そうすると、それらはヌル値として扱われます。 optionsで指定した値は、httpOptionsのパラメータに影響を与え、httpOptionsパラメータをオーバーライドします。 このメソッドは、サポートしていないoptionsおよびhttpOptions引数のプロパティをすべて無視します。

注意:

カスタム・コードからカスタムAPI、プラットフォームAPI、およびカスタムAPIにリクエストを送信するときに、認証について心配する必要はありません。 このサービスは、カスタム・コードに渡されたアクセス・トークンを再利用し、認証を処理します。 コネクタを使用する場合、外部サービスに異なる資格証明を使用する必要がある場合は、options.externalAuthorizationを使用して、外部サービスのAuthorizationヘッダーで使用される値を渡すことができます。

コネクタを経由せずにサードパーティのWebサービスにダイレクト・リクエストを送信する方法については、「カスタム・コードからWebサービスおよびAPIを呼び出す」を参照してください。

共通オプション引数のプロパティ

APIにアクセスするいくつかのカスタム・コードSDKメソッドは、オプションのoptions引数を受け取ります。これはJSONオブジェクトです。 optionsのプロパティは次のとおりです:

プロパティ 説明 タイプ デフォルト値
accept Acceptヘッダーの値。 このプロパティを使用して、レスポンス本文用のメディア・タイプをリストします。 ほとんどのメソッドでは、レスポンス本文のメディア・タイプはapplication/jsonです。 文字列 空。レスポンス・タイプの優先順位を示しません。
contentType Content-Typeヘッダーの値。 このプロパティは、リクエスト本文のコンテンツ・タイプを指定します。 ほとんどのメソッドでは、これはapplication/jsonです。 文字列 inTypejsonの場合、サービスはContent-Typeヘッダーをapplication/jsonに設定します。
inType リクエスト本文をとるストレージ、コネクタAPI、およびカスタムAPI SDK関数の場合、このオプションを使用して、リクエスト本文がjsonまたはstreamのいずれであるかを指定します。

jsonの場合、このメソッドはContent-Typeヘッダーを自動的にapplication/jsonに設定します。

通常、このプロパティは、カスタム・コードがAPIに送信するリクエスト本文を構築するときに設定します。

文字列 未定義。 このプロパティが設定されていない場合、メソッドはリクエスト本文をそのまま渡します。 リクエストはノード・リクエスト・モジュールによって処理され、文字列またはバッファを受け入れます。
outType レスポンス本文タイプ。 値は次のいずれかです。
  • json: レスポンス本文をJSONオブジェクトに変換します。 JSON解析エラーがある場合、レスポンス本文は文字列のままです。

  • stream: レスポンス本文をパイプ可能な読み取り可能なストリームで返します。

  • binary: レスポンス本文を文字列に変換しないでください。

  • encoding: 指定したエンコーディングを使用してレスポンス本文を文字列に変換します。

このプロパティは、Storage API、コネクタおよびカスタムAPIでのみサポートされています。 他のすべてのAPIは、デフォルトのレスポンス動作を使用します。

文字列 未定義。 レスポンス本文は、UTF8エンコーディングを使用して文字列に変換されます。
encodeURI

trueの場合、URIと次の引数とプロパティをエンコードします:

  • tablekeysfieldsextraFieldsprimaryKeyssqldatabaseメソッドの引数とプロパティをエンコード

  • collectionIdmobileNameobjectIdorderByuserの各プロパティとstorageメソッドのプロパティをエンコードします。

このオプションはマルチバイト文字に便利です。

Boolean false

APIレスポンス・パターン

APIへのカスタム・コードSDK呼び出しの戻り値は、options.outTypeプロパティの値によって異なります。

  • outTypestreamの場合、エラーがなければ、戻り値は「ストリームの処理」に示すように、パイプできるストリームです。

  • outTypeが未定義またはstream以外の値である場合、戻り値は約束オブジェクトです。 promiseオブジェクトの詳細については、「約束を処理」を参照してください。

ストリームの処理

レスポンスがstreamの場合、エラーがなければ戻り値はパイプできるストリームです。 それ以外の場合は、次の例に示すようにエラーを処理できます:

  req.oracleMobile.storage.store('attachments', req, {
    mobileName: 'Technician Notes',
    contentType: req.header('content-type'),
    inType: 'stream',
    outType: 'stream'
  })
  .on('error', function (error) {
    res.status(error.status).send(error.message);
  })
  .on('response', function (response) {
    console.info('HEADERS received from response:', response.headers);
  })
  .pipe(res);

ストリーミングの詳細については、https://github.com/request/requestを参照してください。

約束を処理

promiseは、非同期リクエストの結果へのアクセスを提供します。 約束が返された時点で、リクエストは完了していてもいなくてもよい。 ほとんどのカスタム・コードSDKメソッドは約束を返します。 次の例では、<promiseFunction>は、req.oracleMobile.storage.getCollectionsなどの約束を返すカスタム・コードSDKメソッドを表します。

promise関数を呼び出すと、通常はthen関数を使用して、ここに示すように成功または失敗を処理します:

<promiseFunction>.then(successFunction, errorFunction)
  • <promiseFunction>は、次のコード例でreq.oracleMobile.storage.getCollectionsなどの約束を返す呼び出しです。

  • successFunctionは、以前の約束関数が正常に解決された場合に呼び出されるユーザー定義の関数です。 これは、リクエストが400より小さいレスポンス状況コードで完了した場合に発生します。 successFunctionは単一の引数を取ります。これは、以前の<promiseFunction>が成功して返したものです。 カスタム・コードSDKメソッドでは、次のプロパティを持つJSONオブジェクトです:

    • result: 結果の本文。

    • statusCode: HTTPステータス・コード。

    • headers : {accept-charset:'UTF-8',content-type:'application/json'}などのすべてのHTTPレスポンス・ヘッダーを含むJSONオブジェクト。

    • contentType: そのヘッダーがレスポンスに含まれていた場合のContent-Typeヘッダーの値。

    • contentLength: そのヘッダーがレスポンスに含まれていた場合のContent-Lengthヘッダーの値。

  • errorFunctionは、promise関数が正常に解決されない場合に呼び出されるユーザー定義関数です。 これは、レスポンス・ステータスが400以上である場合、または重大なエラーがある場合です。 errorFunctionは1つの引数を取ります。これは、エラー時に<promiseFunction>が返したものです。 カスタム・コードSDKメソッドでは、次のプロパティを持つJSONオブジェクトです:

    • statusCode: HTTPステータス・コード。

    • error: エラーの本文またはエラー・メッセージ。

    • headers: すべてのレスポンスHTTPヘッダー。

注意:

then関数はオプションのprogressFunction引数をとります。 ただし、カスタム・コードSDKではこの引数は使用されず、呼び出しから省略できます。

次に、カスタム・コードSDKメソッドを呼び出してカスタムAPI、プラットフォームAPI、またはコネクタAPIにアクセスし、thenを使用して返される約束を処理する方法の例を示します。 この例では、次のようになります。

  • この例では、<promiseFunction>req.oracleMobile.storage.getCollectionsです。 これは、カスタム・コードSDKのストレージ・コンポーネントからの関数です。これは、約束が成功した場合に解決されるか、エラーの約束が返されて拒否されます。

  • getCollectionsが正常に完了すると、成功した約束をthenの最初の引数function(result)に渡します。

  • getCollectionsがエラーになると、エラー・プロミスが2番目の引数function(error)に渡されます。

// Get metadata about the backend's collections.
service.get('/mobile/custom/incidentreport/collections',
  function (req, res) {
    req.oracleMobile.storage.getCollections({sync: true}).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    ); 
});

約束とその結果を変数に割り当てることができます。 これは、結果が関数呼び出し単独よりも長く続くことができることを意味し、結果に対して複数の成功関数と失敗関数を呼び出すことができます。 たとえば、次のようなコードを書くことができます:

var collections = req.oracleMobile.storage.getCollections({sync: true});

collections.then(successFunction1, errorFunction1);
...
collections.then(successFunction2, errorFunction2);

注意:

カスタム・コードSDKはBluebirdの約束ライブラリを使用するため、このライブラリを使用してこれらの約束を処理することをお勧めします。 promisesライブラリのthen()関数のみを使用する場合は、パッケージにBluebirdを含める必要はありません。

カスタム・コードの実装のために選択できるいくつかの約束ライブラリがありますが、カスタム・コードSDKの約束がどの程度機能するかはわかりません。 Bluebirdの約束については、https://github.com/petkaantonov/bluebirdをご覧ください。

次のセクションでは、約束を処理する方法の一般的な例を示します。

コールの連鎖

一連の呼び出しを同期的に呼び出す必要がある場合、ある操作が完了するのを待ってから次の操作を開始する必要がある場合、ほとんどのカスタム・コードSDKメソッドが約束を返すという事実を利用できます。 約束は、Nodeのような非同期環境で同期呼び出しを行う複雑さのいくつかを処理し、コールバック・メソッドを使用して成功と失敗の両方のケースを処理する簡単な方法を提供します。

「APIレスポンス・パターン」で議論したように、約束の結果を抽出する最も簡単な方法は、then関数を使用することです。 カスタム・コードでは、then関数に2つの引数を指定できます。

  • 成功したときに呼び出す関数。単一の引数をとります。 - 成功の約束。

  • 単一の引数をとるエラー時に呼び出す関数 - エラーの約束。

次に、promise関数の結果を処理するためにthen関数を使用する例を示します。 ご覧のとおり、2つの引数があります:

  • function(result)は、getById結果を送信します。

  • エラー・メッセージを送信するfunction(error)

service.get('/mobile/custom/incidentreport/attachments/:id',
  function (req, res) {
    req.oracleMobile.storage.getById('attachments', req.params.id, {sync: true}).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

ルート定義から複数のAPI操作を呼び出す必要がある場合は、thenを使用して呼び出しを連鎖させることで、ある呼び出しが正常に完了してから次の呼び出しが呼び出されるようにすることができます。 この例では、ルート定義は次のとおりです:

  1. インシデントをデータベースにポストし、結果を返します。

  2. 投稿が正常に完了した場合は、ユーザー情報を取得します。

  3. ユーザー情報が正常に取得されると、アナリティクス・イベントがポストされます。

then関数のいずれも2番目の引数(エラー関数)を受け取っていないことに注意してください。 エラー(拒否された)約束が第2引数を持たないthen関数に渡された場合、コードは第2引数を持つ最初のthen関数にスキップします。 この例では、何もないので、すべてのエラーがcatch関数に流れます。

service.post('/mobile/custom/incidentreport/incidents',
function (req, res) {

  /* Post the incident and send the response. 
   * Then, if the post was successful,
   * get the username,
   * then use the username to post an event.
   * 
   **/
  postIncident()
  .then(getUser)
  .then(postEvent)
  .catch(function (errorResult) {
        console.warn(errorResult);
  });

  function postIncident() {
    return req.oracleMobile.database.insert('FIF_Incidents', req.body)
    .then(
      function (successResult) {
        res.status(successResult.statusCode).send(successResult.result);
        // By default, Bluebird wraps this with a
        // resolved promise
        return {status: "resolved"};
      },
      function (errorResult) {
        res.status(errorResult.statusCode).send(errorResult.error);
        throw errorResult;
      }
    );
  };

  function getUser() {
    return req.oracleMobile.ums.getUser({fields: 'username'});
  };

  function postEvent(successResult) {
    var userName = successResult.result.username;
    /*
     * Record the NewIncident event
     */
    var timestamp = (new Date()).toISOString();
    // Events are posted as an array
    var events = [];
    // Put events in context
    events.push(
      {name: 'context',
        type: 'system',
        timestamp: timestamp,
        properties: {userName: userName}
      });
    // Start the session
    events.push(
      {name: 'sessionStart',
        type: 'system',
        timestamp: timestamp
      });
    // Add the custom event:          
    events.push(
      {name: 'NewIncident',
        type: 'custom',
        component: 'Incidents',
        timestamp: timestamp,
        properties: {customer: req.body.customer}
      });
    // End the session:
    events.push(
      {name: 'sessionEnd',
        type: 'system',
        timestamp: timestamp
      });          
    // Post the batch of events. Apply the passed-in session ID to all.
    // The postEvent result is returned by this function
    return req.oracleMobile.analytics.postEvent(
      events,
      {sessionId: req.header('oracle-mobile-analytics-session-id')});  
  };
});
コールへの参加

Promise.joinでは、いくつかの非同期呼び出しを行い、すべての呼び出しが完了した後に結果を使用できます。 結合が返すという約束は、結果の配列です。

たとえば、次のコードは、結果本文の情報を取得するためにincidentreportカスタムAPIを3回呼び出します。 すべての呼び出しが正常に完了すると、then関数の成功ハンドラが結果をコンパイルするために必要な情報を抽出して送信します。

join関数は、必ずしもコード内で発生する順序で呼び出されるわけではありません。 唯一の保証は、成功の約束が返される前にすべてのjoin関数が正常に完了することです。

/* Promise.join example
 *
 * Promise.join takes multiple promises as arguments.
 * If all promises succeed, then it returns a promise
 * that holds an array of the results of the promises.
 */
var Promise = require("bluebird");
module.exports = function(service) {
  ...
  service.get('/mobile/custom/incidentreport/join/:custId/:incidentId/:techId', function (req, res) {
    // Three functions that return promises.
    var customer = req.oracleMobile.custom.incidentreport.get(
      "customers/" + req.params.custId, {outType: 'json'});
    var incident = req.oracleMobile.custom.incidentreport.get(
      "incidents/" + req.params.incidentId, {outType: 'json'});
    var technician = req.oracleMobile.custom.incidentreport.get(
      "technicians/" + req.params.techId, {outType: 'json'});
 
    Promise.join(customer, incident, technician).then(
      function (joinResult) {
        // Anonymous handler that's called if all 3 promises succeeded.
        // Harvest a piece of data from each promise result.
        var report = {
          customerContact: joinResult[0].result.email, 
          description: joinResult[1].result.title, 
          technicianContact: joinResult[2].result.email};
        res.type('application/json');
        res.status(200).send(report);
      },
      function (error) {
        // Anonymous handler to handle errors
        console.info(error);
        res.status(error.statusCode).send(error.error);
      }
    );
  })  
  ...
}
完了するコールの動的セットを待っている

動的な呼び出しがある場合はPromise.allを使用し、何らかの処置を行う前にすべての呼び出しが完了するまで待つ必要があります。 配列内の約束のいずれかが成功しない場合、返された約束は拒絶の理由とともに拒否されます。

/* Promise.all example
 *
 * Promise.all takes an array of promises as an argument (promiseArray).
 * If all promises succeed, then it returns a promise that holds
 * an array of the results from the promiseArray's promises.
 */

var Promise = require("bluebird");
module.exports = function(service) {
...
  service.get('/mobile/custom/incidentreport/all/:custId/:incidentId/:techId', function (req, res) {
    // Put the functions that return promises in the array
    promiseArray = [];
    promiseArray.push(req.oracleMobile.custom.incidentreport.get(
      "customers/" + req.params.custId, {outType: 'json'}));
    promiseArray.push(req.oracleMobile.custom.incidentreport.get(
      "incidents/" + req.params.incidentId, {outType: 'json'}));
    promiseArray.push(req.oracleMobile.custom.incidentreport.get(
      "technicians/" + req.params.techId, {outType: 'json'}));
    // Call Promise.all with the array
    Promise.all(promiseArray).then(
      function (allResult) {
        var report = {
          customerContact: allResult[0].result.email, 
          description: allResult[1].result.title, 
          technicianContact: allResult[2].result.email};
        res.type('application/json');
        res.status(200).send(report);
      },
      function (error) {
        console.dir(error);
        res.status(error.statusCode).send(error.error);
      }
    );
  })
  ...
}
約束を返す関数の作成

約束を返す関数の作成と使用のいくつかの例を以下に示します。 最初の例は、解決された約束と拒否された約束を返す方法を示しています。

// Simple function that returns a resolved promise.  
// Note the object passed to Promise.resolve is the 
// object the promise is resolved with.
function resolve() {
  return Promise.resolve({status: "resolved"});
}

// Simple function that returns a rejected promise.  
// The object passed to Promise.reject describes the error.
function reject() {
  return Promise.reject({error: "rejected"});
}

この例では、compareEtags関数は引数として成功した(解決された)約束をとります。 リクエストにETagヘッダーがあり、その結果のETagがヘッダーで渡されたETagと一致しない場合、これは約束を拒否します。

var Promise = require("bluebird");
var etag = require('etag');
module.exports = function(service) {
...

  service.get('/mobile/custom/incidentreport/incidents/:id/ifmatch', function (req, res) {
    function compareEtags(result) {
      thisEtag = result.headers.etag;
      if (req.header('if-match') &&
        thisEtag != req.header('if-match')) {
        return Promise.reject({
          statusCode: 412,
          error: "Precondition Failed" +". If-Match ETag: " + req.header('if-match') + ", this Etag: " + thisEtag
        })
      } else {
        // result is already a resolved promise
        return result;
      }
    }
    // The custom code SDK get method returns a promise,
    // which is then passed to the custom function compareEtags.
    // On success, compareEtags passes the result from the get.
    // If there's an ETag header, then the function rejects the 
    // promise if the result's ETag doesn't match.
    // 
    // All rejections are caught by the last then.
    req.oracleMobile.custom.incidentreport.get(
      "incidents/" + req.params.id, {outType: 'json'})
      .then(compareEtags)
      .then(
        function (result) {
          // res.setHeader('Etag', etag(JSON.stringify(result.result)));
          res.status(result.statusCode).send(result.result);
        },
        function (error) {
          res.status(error.statusCode).send(error.error);
        }
      );
  });
...
}

カスタム・コードからのモバイル・バックエンド情報へのアクセス

MBE APIを使用すると、リクエストが送信されたモバイル・バックエンドについて問い合わせることができます。

このAPIには1つのメソッドがあります。

mbe.getMBE()

このメソッドは、リクエストを行ったバックエンドに関する情報を取得します。 このメソッドは同期的であり、約束を返さないことに注意してください。

引数

このメソッドには必須の引数はなく、optionsおよびhttpOptions引数は使用しません。

レスポンス

レスポンス本文は、nameversion、およびidプロパティを含むJSONオブジェクトです。

このメソッドを呼び出して、Notifications APIに渡すバックエンドの名前とバージョン番号を取得する例を次に示します:
  service.get('/mobile/custom/incidentreport/notifications',
    function (req, res) {
      req.oracleMobile.notification.getAll({
        mbe: req.oracleMobile.mbe.getMBE().name,
        version: req.oracleMobile.mbe.getMBE().version})
      .then(
        function (result) {
          res.status(result.statusCode).send(result.result);
        },
        function (error) {
          res.status(error.statusCode).send(error.error);
        }
      );
    });
このメソッドが返すJSONオブジェクトの例を次に示します:
{   
  name: 'myMBE',   
  version: '1.0',   
  id: 'ab72abb7-b337-4673-8584-ca5163df5d24' 
}

カスタム・コードからのプラットフォームAPIの呼び出し

req.oracleMobile.<service>メソッドを使用してプラットフォームAPIを呼び出すことができます。ここで、<service>は呼び出すプラットフォームを示します。 これらのサブセクションでは、各プラットフォームの詳細を示します:

HTTPレスポンス・ステータス・コード、リクエストおよびレスポンス本文のスキーマなどの詳細は、Oracle Mobile Cloud ServiceのREST APIを参照してください。

カスタム・コードからの分析APIのアクセス

Analytics APIを使用すると、ユーザーがお問い合わせを送信したり、アイテムをショッピング・カートに置いたりするなど、ランタイム・イベントを記録して、パフォーマンスや使用パターンを観察できます。

ポストされたイベントで何ができるかおよびどのようにレポートできるかに関する情報は、「分析」を参照してください。

このAPIには1つのメソッドがあります。

analytics.postEvent(events, options, httpOptions)

このメソッドは、イベントのバッチを受け取り、それらを検証します。 これが有効な場合は、分析データベースに送信されます。 バッチ内の1つ以上のイベントが有効でない場合、イベントは分析データベースに送信されません。

バッチにイベントを追加する場合は、次の点に注意してください:

  • イベントには2タイプあります - customおよびsystem カスタム・イベントを使用して、分析するイベントを記録します。 カスタム・イベントをグループ化するには、システム・イベントを使用します。 イベント・タイプを指定しない場合、イベントのデフォルトはcustomです。 各イベントの詳細は、次を参照してください。

  • イベントはJSONオブジェクトです。 すべてのイベントには、nametimestampがあり、componentpropertiesはオプションです。

  • カスタム・イベントでは、独自のカスタム・プロパティをpropertiesに追加できます。 次に例を示します。

    {
      name: 'NewIncident',
      type: 'custom',
      component:  'Incidents', 
      timestamp: timestamp,
      properties: {customer: 'Lynn White'}
    }

    カスタム・プロパティは文字列である必要があり、プロパティ名に予約されている名前を付けることはできません。 予約されている名前のリストは、「イベントへのプロパティの追加」を参照してください。

  • セッションごとにイベントをグループ化できます。 たとえば、セッションでは、アプリケーション内の関数の開始と終了、またはアプリケーションの起動と停止をマークできます。 セッションを開始するには、sessionStartという名前のシステム・イベントを追加します。 セッションを終了するには、sessionEndイベントを使用します。

    イベントをセッションに関連付けるには、ユーザー定義のセッションIDを使用します。 イベントのセッションIDを指定する方法は2つあります。 イベントにsessionIdプロパティを追加し、options.sessionIdプロパティを設定することができます。 セッションの開始と停止の例を次に示します。 これらの例では、セッションIDは明示的に設定されていますが、options.sessionIdを使用して設定することもできます。
    {
      name: 'sessionStart',
      type: 'system',
      sessionId: '2d64d3ff-25c7-4b92-8e49-21884b3495ce',
      timestamp: timestamp
    }
    {
      name: 'sessionEnd',
      type: 'system',
      sessionId: '2d64d3ff-25c7-4b92-8e49-21884b3495ce',
      timestamp: timestamp
    }
  • セッションにコンテキストを提供する場合は、sessionStartイベントの前にcontextというシステム・イベントを付けます。 また、コンテキスト・イベントをカスタム・イベントに散在させて、ロケーションの変更などのコンテキストの変化を示すこともできます。 コンテキスト・イベントの例を次に示します:

    {
      name: 'context',
      type: 'system',
      timestamp: timestamp,
      properties: {
        userName: 'joe',
        model: 'iPhone5,1',
        longitude: '-122.11663',
        latitude: '37.35687',
        manufacturer: 'Apple',
        osName: 'iPhone OS',
        osVersion: '7.1',
        osBuild: '13E28',
        carrier: 'ATT'
    }
  • イベントのバッチをアプリケーションに関連付けるには、アプリケーション・キーに設定されたoptions.applicationKeyプロパティを含めます。

ポストされたイベントで何ができるかおよびどのようにレポートできるかに関する情報は、「分析」を参照してください。

引数

events: Required. これはeventオブジェクトの配列です。 eventプロパティの詳細は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/analytics/events操作に関する項を参照してください。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているプロパティに加えて、これらのプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
applicationKey モバイル・バックエンドへの登録時に、MCSがアプリケーションに割り当てるアプリケーション・キーを識別します。 このキーは、モバイル・バックエンドの「Clients」ページにあります。 例えば、9a5b4150-c756-4758-87c3-ec2814289799です。 文字列 なし
deviceId デバイスを識別します。 これは、デバイスAPIを使用してデバイスをMCSに登録するときに戻されるIDです。 文字列 なし
sessionId デフォルトのセッションIDを指定します。 セッションIDを使用して、すべてのイベントをユーザー定義のセッションでグループ化します。 存在する場合、eventオブジェクトのsessionID値がこの値をオーバーライドします。 文字列 なし

レスポンス

レスポンス本文は、message属性を持つJSONオブジェクトです。 たとえば、{"message":"1 events accepted for processing."}

インシデントの作成時にイベントを記録する例を次に示します。 データベースにインシデントを正常に保存すると、コンテキスト・イベントのユーザー名が取得され、イベントが記録されます。 この例では、promises then()関数を使用して、「コールの連鎖」で説明されているように、各API呼び出しが次の呼び出しを呼び出す前に正常に完了することを保証します。

この例では、リクエスト本文は次のようになります:

{
  title:'Water heater is leaking', 
  technician:'jwhite',
  customer:'Lynn Smith'
}

このコードは、リクエストがOracle-Mobile-Analytics-Session-IDヘッダーにセッションIDを含めることを期待しています。 options.sessionIdプロパティをこの値に設定します。

service.post('/mobile/custom/incidentreport/incidents',
function (req, res) {

  /* Post the incident and send the response. 
   * Then, if the post was successful,
   * get the username,
   * then use the username to post an event.
   * 
   **/
  postIncident()
  .then(getUser)
  .then(postEvent)
  .catch(function (errorResult) {
        console.warn(errorResult);
  });

  function postIncident() {
    return req.oracleMobile.database.insert('FIF_Incidents', req.body)
    .then(
      function (successResult) {
        res.send(successResult.statusCode, successResult.result);
        // By default, Bluebird wraps this with a
        // resolved promise
        return {status: "resolved"};
      },
      function (errorResult) {
        res.send(errorResult.statusCode, errorResult.error);
        throw errorResult;
      }
    );
  };

  function getUser() {
    return req.oracleMobile.ums.getUser({fields: 'username'});
  };

  function postEvent(successResult) {
    var userName = successResult.result.username;
    /*
     * Record the NewIncident event
     */
    var timestamp = (new Date()).toISOString();
    // Events are posted as an array
    var events = [];
    // Put events in context
    events.push(
      {name: 'context',
        type: 'system',
        timestamp: timestamp,
        properties: {userName: userName}
      });
    // Start the session
    events.push(
      {name: 'sessionStart',
        type: 'system',
        timestamp: timestamp
      });
    // Add the custom event:          
    events.push(
      {name: 'NewIncident',
        type: 'custom',
        component: 'Incidents',
        timestamp: timestamp,
        properties: {customer: req.body.customer}
      });
    // End the session:
    events.push(
      {name: 'sessionEnd',
        type: 'system',
        timestamp: timestamp
      });          
    // Post the batch of events. Apply the passed-in session ID to all.
    // The postEvent result is returned by this function
    return req.oracleMobile.analytics.postEvent(
      events,
      {sessionId: req.header('oracle-mobile-analytics-session-id')});  
  };
});

カスタム・コードからのApp Policies APIへのアクセス

アプリ・ポリシーAPIを使用すると、現在のモバイル・バックエンドに設定されているアプリ・ポリシーを取得できます。 たとえば、モバイル・バックエンドには、アプリのメッセージに表示される文字列、バックグラウンド色、タイムアウト値に対するアプリ・ポリシーが設定されている場合があります。

このAPIには1つのメソッドがあります。

appConfig.getProperties(httpOptions)

このメソッドは、モバイル・バックエンドに設定されているアプリ・ポリシーを取得します。 これらは、モバイル・バックエンドの「アプリ・ポリシー」ページから作成するポリシーです。

「アプリ・ポリシー」を参照してください。

引数

このメソッドには必須の引数はなく、options引数は使用しません。

レスポンス

レスポンス本文は、名前/値のペアがアプリ・ポリシーを表すJSONオブジェクトです。

このメソッドを呼び出す例を次に示します:
service.get(
  '/mobile/custom/incidentreport/appPolicies',
  function (req, res) {
    req.oracleMobile.appConfig.getProperties().then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });
レスポンス本文の例を次に示します:
{
  "fifBgColor": "blue",
  "fifWelcomeMessage": "Hello",
  "fifShowArg": true
}

カスタム・コードからのデータベース・アクセスAPIへのアクセス

データベース・アクセスAPIを使用してデータベース表の行を取得、追加、更新および削除できます。 行を追加すると、APIは存在しない場合は暗黙的に表を作成します。

このAPIには、次のメソッドがあります:

これらのメソッドを使用してデータベース表を作成およびアクセスする方法の詳細については、「データベース」を参照してください。

database.delete(table, keys, options, httpOptions)

このメソッドを使用すると、表から行を削除できます。

引数

table: Required. 文字列。 行を削除するデータベース表の名前。

keys: Required. 文字列。 表の行キーがidの場合は、idの値を入力します。 それ以外の場合は、表に最初の行が追加されたときに主キーが指定された順序で主キーの値を指定します(表の作成となります)。 複合キーには配列を使用します。 たとえば、表の作成時にoptions.primaryKeysプロパティがincidentReport,technicianに設定されている場合、その値は['5690','jwhite']のような順序でリストされなければなりません。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているものに加えて、次のプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
encodeURI trueに設定すると、tablekeysの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false

レスポンス

レスポンス本文はJSONオブジェクトです。 表の行キーがidの場合、レスポンスは削除された行のid値を含む配列になります。 それ以外の場合、レスポンスは0または1行が削除されたかどうかを示すrowCountです。

次に、リクエストURIで指定されたidを持つレコードを削除するメソッドを呼び出す例を示します:

service.delete('/mobile/custom/incidentreport/incidents/:id',
  function (req, res) {
    req.oracleMobile.database.delete(
      'FIF_Incidents', req.params.id).then(      
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

このリクエストのレスポンスの例を次に示します。

{"items":[{"id":42}]} 

行キーにシステム定義のid列を使用する代わりに、表の主キーを定義した場合、レスポンスには削除された行のrowCountが表示されます。 次に例を示します。

{
  "rowCount": 1
}
database.get(table, keys, options, httpOptions)

このメソッドを使用すると、表から行を取得できます。

引数

table: Required. 文字列。 行を取り出すデータベース表の名前。

keys: Required. 文字列。 表の行キーがidの場合は、idの値を入力します。 それ以外の場合は、表に最初の行が追加されたときに主キーが指定された順序で主キーの値を指定します(表の作成となります)。 複合キーには配列を使用します。 たとえば、表の作成時にoptions.primaryKeysプロパティがincidentReport,technicianに設定されている場合、その値は['5690','jwhite']のような順序でリストされなければなりません。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているものに加えて、次のプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
encodeURI trueに設定すると、tablekeysの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
expectSingleResult 配列の代わりにオブジェクトを返し、指定されたkeysの行が存在しない場合は404 (見つからない)を返すようにtrueに設定します。 Boolean false

レスポンス

デフォルトでは、レスポンス本文は、列名と対応する値を含む1つのアイテムを持つitems配列を含むJSONオブジェクトです。 単一のオブジェクトを返すには、リクエストにoptions.expectSingleResultを含め、trueに設定します。

次に、リクエストURIで指定されたidを持つ行を取得するメソッドを呼び出す例を示します。 expectSingleResultオプションが省略されているため、レスポンス本文には配列が含まれ、レスポンス・ステータスは常に200になります。

service.get('/mobile/custom/incidentreport/incidents/:id',
  function (req, res) {
    req.oracleMobile.database.get(
      'FIF_Incidents', req.params.id).then(      
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

このリクエストのレスポンスの例を次に示します。

{
  "items":[
    {
      "id":2,
      "createdBy":"jdoe",
      "createdOn":"2018-01-31T20:14:24.4948+00:00",
      "modifiedBy":"jdoe",
      "modifiedOn":"2018-01-31T20:14:24.4948+00:00",
      "title":"Water heater is leaking",
      "technician":"jwhite",
      "status":"Open",
      "customer":"Lynn Smith",
      "incidentReport":"7890"
    }
  ]
}

次に、expectSingleResultオプションにtrueの値を含める例を示します。 レスポンス本文にはオブジェクトが含まれ、行が存在しない場合はレスポンス・ステータスは404になります。

service.get('/mobile/custom/incidentreport/incidents/:id',
  function (req, res) {
    req.oracleMobile.database.get(
      'FIF_Incidents', req.params.id, {expectSingleResult: true}).then(      
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

このリクエストのレスポンスの例を次に示します。

{
    "id": 2,
    "createdBy": "jdoe",
    "createdOn": "2018-01-31T20:14:24.4948+00:00",
    "modifiedBy": "jdoe",
    "modifiedOn": "2018-01-31T20:14:24.4948+00:00",
    "title": "Water heater is leaking",
    "technician": "jwhite",
    "status": "Open",
    "customer": "Lynn Smith",
    "incidentReport": "7890"
}
database.getAll(table, options, httpOptions)

このメソッドを使用すると、表内のすべての行から指定されたフィールドを取得できます。

注意:

Database_MaxRows環境ポリシーは、この呼び出しでサービスが返す行数を制限します。 デフォルト値は1000です。 この値があなたのニーズに十分であることを確認してください。 リクエストが期待したすべての行を返さない場合は、モバイル・クラウド管理者にDatabase_MaxRowsの値を増やすよう依頼してください。

引数

table: Required. 文字列。 行を取り出す表の名前。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているものに加えて、次のプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
encodeURI trueに設定すると、tablefieldsの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
fields 返されるフィールドのコンマ区切りのリスト。 たとえば、customer, statusです。 文字列 この引数を省略すると、このメソッドはすべてのフィールドを返します。

レスポンス

レスポンス本文はitems配列を含むJSONオブジェクトです。各アイテムは行を表し、列名と対応する値を含みます。

次に、FIF_Incidents表からcustomerstatusフィールドを取得するメソッドの呼び出しの例を示します:

service.get('/mobile/custom/incidentreport/incidents',
function (req, res) {
    req.oracleMobile.database.getAll(
      'FIF_Incidents', {fields: 'customer,status'}).then(    
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

このリクエストのレスポンスの例を次に示します。

{
  "items":[
    {
      "status":"Open",
      "customer":"Lynn Smith"
    },
    {
      "status":"Completed",
      "customer":"John Doe"
    }
  ]
}

/database/objects/{table}リソースは、検索する行の列値をフィルタリングするための問合せパラメータをサポートしています。 この例では、httpOptions引数を使用して、一致する技術者の結果をフィルタするリクエスト問合せ文字列を渡します。

service.get('/mobile/custom/incidentreport/incidents',
function (req, res) {
    httpOptions={};
    httpOptions.qs = {technician : 'jwhite'};
    req.oracleMobile.database.getAll(
      'FIF_Incidents', {}, httpOptions).then(    
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });
database.insert(table, object, options, httpOptions)

このメソッドを使用すると、1つまたは複数の行を表に追加できます。

Database_CreateTablesPolicy環境ポリシーがallowの場合、次のアクションが発生する可能性があります:

  • 表が存在しない場合は作成されます。

  • 列が存在しない場合は、表がその列を含むように変更されます。

  • 値が列サイズより大きい場合は、列のサイズが変更されます。

Database_CreateTablesPolicy環境ポリシーの設定については、モバイル・クラウド管理者に問い合わせてください。

引数

table: Required. 文字列。 行を追加するデータベース表の名前。

object: Required. 表データを含むJSONオブジェクト。 1つの行を追加する場合は、次の形式を使用できます:

{ 
  status : 'Open',
  code : '3'
}

複数の行を追加する場合は、次の形式を使用します:

[
    {
        status:'Open',
        code:3},
    {
        status:'Completed',
        code:9}
]

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているものに加えて、次のプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
encodeURI trueに設定すると、tableextraFields、およびprimaryKeysの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
extraFields 暗黙的な表作成の場合、オプションで、idcreatedBycreatedOnmodifiedBy、およびmodifiedOnの中から表に組み込む事前定義列を指定するカンマ区切りリストを指定します。 たとえば、createdOn,createdByです。

事前定義された列を含まない場合は、noneを指定します。

文字列 定義済みの列をすべて含めるには、このプロパティを含めないでください。 primaryKeysextraFieldsの両方のプロパティが存在しない場合は、id列が自動的に表に追加されます。
primaryKeys 暗黙の表を作成するには、リクエスト本文のJSONオブジェクトのどの属性が表の主キーを構成するかを指定する、URLエンコードされたコンマ区切りのリストを提供します。 例えば、lastName,firstNameです。

注意:

表のメタデータから主キーの順序を取得することはできないため、プライマリ・フィールドの順序を文書化してください。
文字列 主キーを指定しない場合、サービスはid列を表に追加し、extraFieldsをリストに含めない場合は自動的に列値を生成します。

レスポンス

レスポンス本文はJSONオブジェクトです。 表がidで索引付けされている場合、レスポンスは新しい行のid値の配列になります。 それ以外の場合、レスポンスは追加されたレコードのrowCountです。

次に、メソッドを呼び出して2行を追加する例を示します。 表が存在しない場合、サービスによって表が作成されます。 この表には余分なフィールドはなく、その主キーはcodeです:

service.post('/mobile/custom/incidentreport/initStatus', function (req, res) {
  req.oracleMobile.database.insert(
    'FIF_Status',
    [
      {
        status: 'Closed',
        code: '0'},
      {
        status: 'Completed',
        code: '9'}
    ],
    {extraFields: 'none', primaryKeys: 'code'}).then(
    function (result) {
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      res.status(error.statusCode).send(error.error);
    }
  );
});

このリクエストのレスポンスの例を次に示します。

{
  "rowCount": 2
}

表の行キーが(ユーザー定義の主キーではなく)システム定義のid列である場合、レスポンスは新しい行のid値を示します。 次に例を示します。

{"items":[{"id":42},{"id":43}]} 
database.merge(table, object, options, httpOptions)

このメソッドを使用すると、表内の行を追加または更新できます。 操作が追加または更新を実行するかどうかは、表がidまたは主キー・フィールドを使用して行を一意に識別するかどうかによって異なります。

  • idフィールド: object引数の表データにidプロパティを組み込むと、操作は更新を実行します。 それ以外の場合は、行が追加されます。

  • 主キー・フィールド: 表が主キー・フィールドを使用する場合、一致する主キー値を持つ行が存在する場合、操作は更新を実行します。 それ以外の場合は、行が追加されます。

行のバッチを送信する場合、すべての行に同じ列のセットが必要であることに注意してください。

Database_CreateTablesPolicy環境ポリシーがallowの場合、次のアクションが発生する可能性があります:

  • 表が存在しない場合は作成されます。

  • 列が存在しない場合は、表がその列を含むように変更されます。

  • 値が列サイズより大きい場合は、列のサイズが変更されます。

Database_CreateTablesPolicy環境ポリシーの設定については、モバイル・クラウド管理者に問い合わせてください。

引数

table: Required. 文字列。 行を追加するデータベース表の名前。

object: Required. 表データを含むJSONオブジェクト。 1つの行を追加する場合は、次の形式を使用できます:

{ 
  status : 'Open',
  code : '3'
}

複数の行を追加する場合は、次の形式を使用します:

[
    {
        status:'Open',
        code:'3'},
    {
        status:'Completed',
        code:'9'}
]

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているものに加えて、次のプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
encodeURI trueに設定すると、tableextraFields、およびprimaryKeysの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
extraFields 暗黙的な表作成の場合、オプションで、idcreatedBycreatedOnmodifiedBy、およびmodifiedOnの中から表に組み込む事前定義列を指定するカンマ区切りリストを指定します。 たとえば、createdOn,createdByです。

事前定義された列を含まない場合は、noneを指定します。

文字列 定義済みの列をすべて含めるには、このプロパティを含めないでください。 primaryKeysextraFieldsの両方のプロパティが存在しない場合は、id列が自動的に表に追加されます。
primaryKeys 暗黙の表を作成するには、リクエスト本文のJSONオブジェクトのどの属性が表の主キーを構成するかを指定する、URLエンコードされたコンマ区切りのリストを提供します。 例えば、lastName,firstNameです。

注意:

表のメタデータから主キーの順序を取得することはできないため、プライマリ・フィールドの順序を文書化してください。
文字列 主キーを指定しない場合、id列は表に追加され、extraFieldsをリストに含めない場合は自動的に列値が生成されます。

レスポンス

レスポンス本文はJSONオブジェクトです。 表がidで索引付けされている場合、レスポンスは新しい行のid値の配列になります。 それ以外の場合、レスポンスはrowCountです。

次に、メソッドを呼び出して2行を追加または更新する例を示します。 表が存在しない場合、操作によって表が作成されます。 この表には余分なフィールドはなく、その主キーはcodeです:

service.post('/mobile/custom/incidentreport/initStatus', function (req, res) {
  req.oracleMobile.database.merge(
    'FIF_Status',
    [
      {
        status: 'Closed',
        code: '0'},
      {
        status: 'Completed',
        code: '9'}
    ],
    {extraFields: 'none', primaryKeys: 'code'}).then(
    function (result) {
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      res.status(error.statusCode).send(error.error);
    }
  );
});

このリクエストのレスポンスの例を次に示します。

{
  "rowCount": 2
}

表の行キーが(ユーザー定義の主キーではなく)システム定義のid列である場合、レスポンスは新しい行のid値を示します。 次に例を示します。

{"items":[{"id":42},{"id":43}]} 

カスタム・コードからのデバイスAPIのアクセス

このAPIを使用して、モバイル・アプリを実行しているデバイスが通知を受信できるように構成します。

このAPIには、次のメソッドがあります:

devices.deregister(device, httpOptions)

このメソッドを呼び出して、通知を受け取る必要がなくなったモバイル・クライアント・インスタンスを登録解除します。

引数

device: Required. Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/devices/deregisterの操作に示されている、ルート(モバイル・クライアント・インスタンス)リクエスト・スキーマに従うJSONオブジェクトです。

notificationProviderプロパティが指定されていない場合、サービスはiOSではAPNS、AndroidではGCM、WindowsではWNSとみなされます。

次に、このメソッドを呼び出してデバイスの登録を解除する例を示します。

service.post(
  '/mobile/custom/incidentreport/devices/deregister',
  function (req, res) {
    req.oracleMobile.devices.deregister(
      {
        "notificationToken": "b14d6dfbd9d56e09f098",
        "notificationProvider: "APNS",
        "mobileClient": {
          "id": "my.app.id",
          "platform": "IOS"
        }
      }
    ).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });
devices.register(device, httpOptions)

このメソッドを呼び出して、新しいデバイスを登録します。

引数

device: Required. Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/devices/registerの操作に示されている、ルート(モバイル・クライアント・インスタンス)リクエスト・スキーマに従うJSONオブジェクトです。

レスポンス

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/devices/registerの操作に示されているルート(モバイル・クライアント・インスタンス)のレスポンス・スキーマに従うJSONオブジェクトです。

次に、このメソッドを呼び出してデバイスを登録する例を示します。

service.post(
  '/mobile/custom/incidentreport/devices/register',
  function (req, res) {
    req.oracleMobile.devices.register(
      {
        "notificationToken": "b14d6dfbd9d56e09f098",
        "notificationProvider: "APNS",
        "mobileClient": {
          "id": "my.app.id",
          "version": "1.0",
          "platform": "IOS"
        }
      }
    ).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

レスポンス本文の例を次に示します:

{
  "id": "27fee547-bdd0-4688-9497-475ec5ed0dfd",
  "notificationToken": "b14d6dfbd9d56e09f098",
  "notificationProvider: "APNS",
  "mobileClient": {
    "id": "my.app.id",
    "user": "joe",
    "version": "1.0",
    "platform": "IOS"
  },
  "modifiedOn": "2015-06-17T18:37:59.424Z"
}

カスタム・コードからロケーションAPIにアクセス

ロケーションAPIでは、ロケーション・デバイス、そのアセット、およびそれらが配置されている場所について問い合わせることができます。

このAPIには、次のメソッドがあります:

「ロケーション」では、ロケーション・デバイス、アセット、および場所について学ぶことができます。

アセット、デバイス、および場所を追加、削除、および更新するメソッドについては、「カスタム・コードからロケーション管理APIにアクセス」を参照してください。

location.assets.getAsset(id, httpOptions)

このメソッドを呼び出して、指定されたIDまたは名前に一致するアセットを取得します。

引数

id: 必須。 次のいずれかの値である必要があります。

  • 取得するアセットのIDを含む文字列。

  • プロパティ値が検索値を示すidプロパティまたはnameプロパティのいずれかを含むJSONオブジェクト。 オブジェクトに両方のプロパティが含まれている場合、SDKは一致する名前のアセットを取得します。

レスポンス

レスポンス本文は、「Oracle Mobile Cloud ServiceのREST API」GET /mobile/platform/location/assetsおよびGET /mobile/platform/location/assets/{id}操作用に表示されるAssetスキーマに続くJSONオブジェクトです

次に、このメソッドを呼び出してIDでアセットを取得する例を示します。

service.get(
  '/mobile/custom/incidentreport/assets/:id',
  function (req, res) {
    req.oracleMobile.location.assets.getAsset(req.params.id).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

次に、このメソッドを呼び出してアセットを名前で取得する例を示します。

service.get(
  '/mobile/custom/incidentreport/assets/:name',
  function (req, res) {
    req.oracleMobile.location.assets.getAsset({name:req.params.name}).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

レスポンス本文の例を次に示します:

{
   "id":111,
   "createdOn":"2015-08-06T18:37:59.424Z",
   "createdBy":"jdoe",
   "modifiedOn":"2015-08-06T18:37:59.424Z",
   "modifiedBy":"jdoe",
   "name":"RC_WH_01_F01_B023",
   "label":"forklift",
   "description":"Forklift in the FixItFast Warehouse in Redwood City",
   "lastKnownLocation":{
      "gpsPoint":{
         "latitude":37.5548,
         "longitude":-121.1566
      }
   },
   "devices":[
      {
         "id":345,
         "createdOn":"2015-08-06T18:37:59.424Z",
         "createdBy":"jdoe",
         "modifiedOn":"2015-08-08T07:22:44.654Z",
         "modifiedBy":"tsmith",
         "name":"RC_WH_01_F01_B001",
         "description":"Beacon in FixitFast Warehouse in Redwood City",
         "beacon":{
            "iBeacon":{
               "uuid":"B9407F30-F5F8-466E-AFF9-25556B57FE6D",
               "major":"1.0",
               "minor":"1.1"
            }
         },
         "attributes":{
            "manufacturer":"Abc Company",
            "manufacturerId":"10D39AE7-020E-4467-9CB2-DD36366F899D",
            "status":"Active",
            "visibility":"Public"
         },
         "links":[
            {
               "rel":"canonical",
               "href":"/mobile/platform/location/devices/345"
            },
            {
               "rel":"self",
               "href":"/mobile/platform/location/devices/345"
            }
         ]
      }
   ],
   "attributes":{
      "EquipmentManufacturer":"Abc Company",
      "beaconID":"AE2924505-66045"
   },
   "links":[
      {
         "rel":"canonical",
         "href":"/mobile/platform/location/assets/111"
      },
      {
         "rel":"self",
         "href":"/mobile/platform/location/assets/111"
      }
   ]
}
location.assets.query(queryObject, httpOptions)

queryObjectで指定した問合せパラメータに一致するアセットを取得するには、このメソッドを呼び出します。

引数

queryObject: 必須。 文字列。 目的の結果を説明するパラメータ。 詳細は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/location/assets/query操作の本文パラメータに関する項を参照してください。 問合せパラメータがない場合は、空の本文({})を使用します。

レスポンス

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/location/assets/query操作に示されているAssetスキーマに従うアイテムの配列を含むJSONオブジェクトです。 結果にはページング情報も含まれます。 次に例を示します。

"totalResults":2,
"offset":0,
"limit":40,
"count":2,
"hasMore":false

次に、このメソッドを呼び出す例を示します。 これは、名前または説明(大文字小文字を区別しない)に文字列1225を持つすべてのアセットを返します。
service.get(
  '/mobile/custom/incidentreport/assets,
  function (req, res) {
    req.oracleMobile.location.assets.query({"search":"1225"}).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });
レスポンス本文の例を次に示します:
{
    "items":[
        {
            "devices":[
                {
                    "id":3401,
                    "createdBy":"jdoe",
                    "name":"RC_WH_01_F01_B001",
                    "createdOn":"2015-08-06T18:37:59.424Z",
                    "modifiedOn":"2015-08-08T07:22:44.654Z",
                    "beacon":{
                        "iBeacon":{
                            "uuid":"B9407F30-F5F8-466E-AFF9-25556B57FE6D",
                            "major":"1.0",
                            "minor":"1.1"}},
                    "modifiedBy":"tsmith",
                    "links":[
                        {
                            "rel":"canonical",
                            "href":"/mobile/platform/location/devices/3401"},
                        {
                            "rel":"self",
                            "href":"/mobile/platform/location/devices/3401"}
                    ],
                    "attributes":{
                        "manufacturer":"Example Company",
                        "manufacturerId":"10D39AE7-020E-4467-9CB2-DD36366F899D",
                        "status":"Active",
                        "visibility":"Public"},
                    "description":"Beacon on 1st Floor in FixitFast Warehouse in Redwood City"}
            ],
            "label":"hospital bed",
            "lastKnownLocation":{
                "placeId":244},
            "id":333,
            "createdBy":"jdoe",
            "name":"hospital bed #233",
            "createdOn":"2015-08-06T18:37:59.424Z",
            "modifiedOn":"2015-08-06T18:37:59.424Z",
            "modifiedBy":"jdoe",
            "links":[
                {
                    "rel":"canonical",
                    "href":"/mobile/platform/location/assets/333"},
                {
                    "rel":"self",
                    "href":"/mobile/platform/location/assets/333"}
            ],
            "attributes":{
                "EquipmentManufacturer":"Example Company",
                "SJId":"6754843090"},
            "description":"model 1225 hospital bed"},
        {
            "devices":[
                {
                    "id":648,
                    "createdBy":"jdoe",
                    "name":"RC_WH_01_F01_B001",
                    "createdOn":"2015-08-06T18:37:59.424Z",
                    "modifiedOn":"2015-08-08T07:22:44.654Z",
                    "beacon":{
                        "iBeacon":{
                            "uuid":"B9407F30-F5F8-466E-AFF9-25556B57FE6D",
                            "major":"1.0",
                            "minor":"1.1"}},
                    "modifiedBy":"tsmith",
                    "links":[
                        {
                            "rel":"canonical",
                            "href":"/mobile/platform/location/devices/648"},
                        {
                            "rel":"self",
                            "href":"/mobile/platform/location/devices/648"}
                    ],
                    "attributes":{
                        "manufacturer":"Example Company",
                        "manufacturerId":"10D39AE7-020E-4467-9CB2-DD36366F899D",
                        "status":"Active",
                        "visibility":"Public"},
                    "description":"Beacon on 1st Floor in FixitFast Warehouse in Redwood City"}
            ],
            "label":"hospital bed",
            "lastKnownLocation":{
                "placeId":360},
            "id":888,
            "createdBy":"jdoe",
            "name":"hospital bed #233",
            "createdOn":"2015-10-16T09:24:41.354Z",
            "modifiedOn":"2015-10-16T09:24:41.354Z",
            "modifiedBy":"jdoe",
            "links":[
                {
                    "rel":"canonical",
                    "href":"/mobile/platform/location/assets/888"},
                {
                    "rel":"self",
                    "href":"/mobile/platform/location/assets/888"}
            ],
            "attributes":{
                "EquipmentManufacturer":"Example Company",
                "SJId":"6754843090"},
            "description":"model 1225 hospital bed"}
    ],
    "totalResults":2,
    "offset":0,
    "count":2,
    "hasMore":false
}
location.devices.getDevice(id, httpOptions)

このメソッドを呼び出して、指定されたIDまたは名前に一致するデバイスを取得します。

引数

id: 必須。 次のいずれかの値である必要があります。

  • 取得するデバイスのIDを含む文字列。

  • プロパティ値が検索値を示すidプロパティまたはnameプロパティのいずれかを含むJSONオブジェクト。 オブジェクトに両方のプロパティが含まれている場合、SDKは一致する名前のデバイスを取得します。

レスポンス

レスポンス本文は、「Oracle Mobile Cloud ServiceのREST API」GET /mobile/platform/location/devicesおよびGET /mobile/platform/location/devices/{id}操作のために表示されるLocation deviceスキーマに続くJSONオブジェクトです。

次に、このメソッドを呼び出してIDでデバイスを取得する例を示します。

service.get(
  '/mobile/custom/incidentreport/devices/:id',
  function (req, res) {
    req.oracleMobile.location.devices.getDevice(req.params.id).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

次に、このメソッドを呼び出して名前でデバイスを取得する例を示します。

service.get(
  '/mobile/custom/incidentreport/devices/:name',
  function (req, res) {
    req.oracleMobile.location.devices.getDevice({name:req.params.name}).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

レスポンス本文の例を次に示します:

{
  "id": 12345,
  "createdOn": "2015-08-06T18:37:59.424Z",
  "createdBy": "jdoe",
  "modifiedOn": "2015-08-08T07:22:44.654Z",
  "modifiedBy": "tsmith",
  "name": "RC_WH_01_F01_B001",
  "description": "Beacon on 1st Floor in FixitFast Warehouse in Redwood City",
  "place":
  {
    "id": 111,
    "createdOn": "2015-08-06T18:37:59.424Z",
    "createdBy": "jdoe",
    "modifiedOn": "2015-08-06T18:37:59.424Z",
    "modifiedBy": "jdoe",
    "name": "FixitFast Redwood City Warehouse",
    "label": "FixitFast Warehouse",
    "parentPlace": 42,
    "description": "FixitFast Warehouse in Redwood City",
    "address" : {
      "gpsPoint" : {
        "latitude": 37.5548,
        "longitude": -121.1566
      }
    },
    "attributes" : {
      "equipmentManufacturer": "Abc Corp"
    },
    "links": [
      {
        "rel": "canonical",
        "href": "/mobile/platform/location/places/111"
      },
      {
        "rel": "self",
        "href": "/mobile/platform/location/places/111"
      }
    ]
  },
  "beacon": {
    "iBeacon" : {
      "uuid": "B9407F30-F5F8-466E-AFF9-25556B57FE6D",
      "major": "1.0",
      "minor": "1.1"
    }
  },
  "attributes" : {
    "manufacturer": "Abc Company",  
    "manufacturerId": "10D39AE7-020E-4467-9CB2-DD36366F899D"
    "status": "Active",
    "visibility": "Public"
  },
  "links": [
    {
      "rel": "canonical",
      "href": "/mobile/platform/location/devices/12345"
    },
    {
      "rel": "self",
      "href": "/mobile/platform/location/devices/12345"
    }
  ]
} 
location.devices.query(queryObject, httpOptions)

queryObjectで指定した問合せパラメータに一致するデバイスを取得するには、このメソッドを呼び出します。

引数

queryObject: 必須。 文字列。 目的の結果を説明するパラメータ。 詳細は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/location/devices/query操作の本文パラメータに関する項を参照してください。 問合せパラメータがない場合は、空の本文({})を使用します。

レスポンス

レスポンス本文は、POST /mobile/platform/location/devices/query操作のLocation deviceスキーマに続くアイテムの配列を含むJSONオブジェクトです。この結果には、ページング情報も含まれています。 次に例を示します。

"totalResults":2,
"offset":0,
"limit":40,
"count":2,
"hasMore":false

次に、このメソッドを呼び出す例を示します。 名前または説明(大文字小文字を区別しない)の文字列warehouseを持つデバイスを返します。
service.get(
  '/mobile/custom/incidentreport/devices,
  function (req, res) {
    req.oracleMobile.location.devices.query({{ "search": "Warehouse"}}).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });
レスポンス本文の例を次に示します:
{
    "items":[
        {
            "id":33,
            "name":"RC_WH_01_B09_C004",
            "description":"Beacon on 2nd Floor NW in FixItFast Warehouse in Redwood City",
            "protocol":"altBeacon"},
        {
            "id":12,
            "name":"RC_WH_01_F01_B001",
            "description":"Beacon on 1st Floor SE in FixItFast Warehouse in Redwood City",
            "protocol":"altBeacon"},
        {
            "id":61,
            "name":"RC_WH_01_F01_B008",
            "description":"Beacon on 2nd Floor SW in FixItFast Warehouse in Redwood City",
            "protocol":"altBeacon"},
        {
            "id":58,
            "name":"RC_WH_02_F01_B011",
            "description":"Beacon on 1st Floor NW in FixitFast Warehouse in Redwood City",
            "protocol":"altBeacon"},
        {
            "id":114,
            "name":"RC_WH_01_K22_A999",
            "description":"Beacon on 3rd Floor NW in FixitFast Warehouse in Redwood City",
            "protocol":"altBeacon"}
    ],
    "totalResults":5,
    "offset":0,
    "count":5,
    "hasMore":false
}
location.places.getPlace(id, httpOptions)

このメソッドを呼び出して、指定されたIDまたは名前と一致する場所を取得します。

引数

id: 必須。 次のいずれかの値である必要があります。

  • 取得する場所のIDを含む文字列。

  • プロパティ値が検索値を示すidプロパティまたはnameプロパティのいずれかを含むJSONオブジェクト。 オブジェクトに両方のプロパティが含まれている場合、SDKは一致する名前の場所を取得します。

レスポンス

レスポンス本文は、「Oracle Mobile Cloud ServiceのREST API」GET /mobile/platform/location/placesおよびGET /mobile/platform/location/places/{id}操作のために表示されるPlaceスキーマに続くJSONオブジェクトです。

次に、このメソッドを呼び出してIDで場所を取得する例を示します。

service.get(
  '/mobile/custom/incidentreport/places/:id',
  function (req, res) {
    req.oracleMobile.location.places.getPlace(req.params.id).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

次に、このメソッドを呼び出して名前で場所を取得する例を示します。

service.get(
  '/mobile/custom/incidentreport/places/:name',
  function (req, res) {
    req.oracleMobile.location.places.getPlace({name:req.params.name}).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

レスポンス本文の例を次に示します:

{
  "id": 111,
  "createdOn": "2015-08-06T18:37:59.424Z",
  "createdBy": "jdoe",
  "modifiedOn": "2015-08-06T18:37:59.424Z",
  "modifiedBy": "jdoe",
  "name": "FixitFast Redwood City Warehouse",
  "label": "FixitFast Warehouse",
  "parentPlace": 42,
  "description": "FixitFast Warehouse in Redwood City",
  "address" : {
    "gpsPoint" : {
      "latitude": 37.5548,
      "longitude": -121.1566
    }
  },
  "attributes" : {
    "equipmentManufacturer": "Abc Corp"
  },
  "links": [
    {
      "rel": "canonical",
      "href": "/mobile/platform/location/places/111"
    },
    {
      "rel": "self",
      "href": "/mobile/platform/location/places/111"
    }
  ]
}  
location.places.query(queryObject, httpOptions)

このメソッドを呼び出して、queryObjectで指定した問合せプロパティに一致する場所と、オプションで関連するデバイスを取得します。

引数

queryObject: 必須。 文字列。 目的の結果を説明するパラメータ。 詳細は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/location/places/query操作の本文パラメータに関する項を参照してください。 問合せパラメータがない場合は、空の本文({})を使用します。

レスポンス

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/location/places/query操作に示されているPlaceスキーマに従うアイテムの配列を含むJSONオブジェクトです。 結果にはページング情報も含まれます。 次に例を示します。
"totalResults":2,
"offset":0,
"limit":40,
"count":2,
"hasMore":false

次に、このメソッドを呼び出す例を示します。 名前または説明(大文字小文字を区別しない)に文字列warehouseを持つすべての場所を返します。 デフォルトでは、レスポンスにはchildren配列が含まれています。この配列には、子孫の場所に関する情報が含まれています。 このリクエストでは、includeDescendantsInResultプロパティはnoneに設定されます。 したがって、リクエストにはその配列は含まれません。
service.get(
  '/mobile/custom/incidentreport/places',
  function (req, res) {
    req.oracleMobile.location.places.query({"search":"warehouse","includeDescendantsInResult":"none" }).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

レスポンス本文の例を次に示します:

{
    "items":[
        {
            "devices":[
                {
                    "id":12345,
                    "createdBy":"jdoe",
                    "name":"RC_WH_01_F01_B001",
                    "createdOn":"2015-08-06T18:37:59.424Z",
                    "modifiedOn":"2015-08-08T07:22:44.654Z",
                    "beacon":{
                        "iBeacon":{
                            "uuid":"B9407F30-F5F8-466E-AFF9-25556B57FE6D",
                            "major":"1.0",
                            "minor":"1.1"}},
                    "modifiedBy":"tsmith",
                    "links":[
                        {
                            "rel":"canonical",
                            "href":"/mobile/platform/location/devices/12345"},
                        {
                            "rel":"self",
                            "href":"/mobile/platform/location/devices/12345"}
                    ],
                    "attributes":{
                        "manufacturer":"Abc Company",
                        "manufacturerId":"10D39AE7-020E-4467-9CB2-DD36366F899D",
                        "status":"Active",
                        "visibility":"Public"},
                    "description":"Beacon on 1st Floor in FixitFast Warehouse in Redwood City"}
            ],
            "label":"FixItFast Warehouse",
            "id":112,
            "createdBy":"jdoe",
            "name":"FixItFast Redwood City Warehouse",
            "createdOn":"2015-08-06T18:37:59.424Z",
            "modifiedOn":"2015-08-06T18:37:59.424Z",
            "address":{
                "gpsPoint":{
                    "latitude":122,
                    "longitude":37}},
            "modifiedBy":"jdoe",
            "links":[
                {
                    "rel":"canonical",
                    "href":"/mobile/platform/location/places/112"},
                {
                    "rel":"self",
                    "href":"/mobile/platform/location/places/112"}
            ],
            "attributes":{
                "hours":"9am-6pm"},
            "hasChildren":false,
            "parentPlace":42,
            "description":"FixItFast Warehouse in Redwood City"},
        {
            "devices":[
                {
                    "id":111,
                    "createdBy":"jdoe",
                    "name":"RC_WH_01_F01_B001",
                    "createdOn":"2015-08-06T18:37:59.424Z",
                    "modifiedOn":"2015-08-08T07:22:44.654Z",
                    "beacon":{
                        "iBeacon":{
                            "uuid":"B9407F30-F5F8-466E-AFF9-25556B57FE6D",
                            "major":"1.0",
                            "minor":"1.1"}},
                    "modifiedBy":"tsmith",
                    "links":[
                        {
                            "rel":"canonical",
                            "href":"/mobile/platform/location/devices/111"},
                        {
                            "rel":"self",
                            "href":"/mobile/platform/location/devices/111"}
                    ],
                    "attributes":{
                        "manufacturer":"Abc Company",
                        "manufacturerId":"10D39AE7-020E-4467-9CB2-DD36366F899D",
                        "status":"Active",
                        "visibility":"Public"},
                    "description":"Beacon on 1st Floor in FixitFast Warehouse in Redwood City"},
                {
                    "id":222,
                    "createdBy":"jdoe",
                    "name":"RC_WH_01_F01_B996",
                    "createdOn":"2015-08-08T18:37:59.424Z",
                    "modifiedOn":"2015-08-12T07:22:44.654Z",
                    "beacon":{
                        "iBeacon":{
                            "uuid":"B9407F30-F5F8-466E-AFF9-25552345908234DD0",
                            "major":"1.0",
                            "minor":"1.1"}},
                    "modifiedBy":"tsmith",
                    "links":[
                        {
                            "rel":"canonical",
                            "href":"/mobile/platform/location/devices/222"},
                        {
                            "rel":"self",
                            "href":"/mobile/platform/location/devices/222"}
                    ],
                    "attributes":{
                        "manufacturer":"Abc Company",
                        "manufacturerId":"10D39AE7-020E-4467-9CB2-DD36366F899D",
                        "status":"Active",
                        "visibility":"Public"},
                    "description":"Beacon on 2nd Floor in FixitFast Warehouse in Redwood City"}
            ],
            "label":"FixItFast Warehouse",
            "id":325,
            "createdBy":"jdoe",
            "name":"FixItFast Palo Alto Warehouse",
            "createdOn":"2015-08-06T19:27:59.424Z",
            "modifiedOn":"2015-08-06T19:27:59.424Z",
            "address":{
                "gpsCircle":{
                    "latitude":123,
                    "longitude":37,
                    "radius":300}},
            "modifiedBy":"jdoe",
            "links":[
                {
                    "rel":"canonical",
                    "href":"/mobile/platform/location/places/325"},
                {
                    "rel":"self",
                    "href":"/mobile/platform/location/places/325"}
            ],
            "attributes":{
                "hours":"9am-6pm"},
            "hasChildren":false,
            "parentPlace":42,
            "description":"FixItFast Warehouse in Palo Alto"}
    ],
    "totalResults":2,
    "offset":0,
    "count":2,
    "hasMore":false
}

カスタム・コードからロケーション管理APIにアクセス

ロケーション管理APIを使用すると、ロケーションのデバイス、場所、およびアセットを作成、更新、削除できます。

「ロケーション」では、ロケーション・デバイス、アセット、および場所について学ぶことができます。

これらのメソッドのAuthorizationリクエスト・ヘッダーは、OAUTHを使用する必要があります。 それ以外の場合、メソッドは404 HTTPステータス・コードを返します。

このAPIには、次のメソッドがあります:

アセット、デバイス、および場所に関する情報を問合せおよび取得するメソッドについては、「カスタム・コードからロケーションAPIにアクセス」を参照してください。

ロケーション管理コンテキスト引数

すべてのLocation Management APIメソッドには、context引数が必要です。これは、次のプロパティを持つJSONオブジェクトです。 この情報は、ロケーション情報を管理するための認証を得るために必要です。 また、モバイル・アプリはOAuth認証を使用する必要があります。

カスタム・コードはmbe.getMBE()を呼び出してモバイル・バックエンド情報を取得できることに注意してください。

プロパティ 説明 タイプ
mbe モバイル・バックエンドの名前。 文字列
username MCSチーム・メンバーでありMobileEnvironment_Systemロールを持ったユーザーの名前。 チーム・メンバーとそのロールは、「Oracle Cloud Infrastructure Classicコンソール」から管理されます。 「MCSチーム・メンバー・ロールの割当て」を参照してください。 文字列
version モバイル・バックエンドのバージョン。 文字列

注意:

Authorizationリクエスト・ヘッダーがOAuthを使用していない場合、メソッドは404を返します。 usernameMobileEnvironment_Systemロールを持ったMCSチームのメンバーでない場合、メソッドは403を返します。
location.assets.register(assets, context, httpOptions)

このメソッドを使用すると、1つ以上のアセットを作成できます。

引数

assets: Required. Oracle Mobile Cloud ServiceのREST APIPOST /mobile/system/locationManagement/assetsの操作に示されているリクエスト・ルート・スキーマ(Assets Array)に従うJSONオブジェクトです。 次に例を示します。

{
  "items":[
      {
          "name":"hospital bed #233",
          "label":"hospital bed",
          "description":"model 1225 hospital bed",
          "lastKnownLocation":{
              "placeId":244
          },
          "devices":[
              1111
          ],
          "attributes":{
              "EquipmentManufacturer":"Example Company",
              "SJId":"6754843090"
          }
      }
  ]
}

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

レスポンス

格納されたアセットを示すレスポンス本文は、REST APIs for Oracle Mobile Cloud ServicePOST /mobile/system/locationManagement/assetsの操作に示されているレスポンス・ルート・スキーマ(Assets Array)に従うJSONオブジェクトです。

この例では、リクエスト本文は次のようになります:
{
  "userName":"anAdministrator",
  "assets": {
    "items":[
      {
        "name":"hospital bed #233",
        "label":"hospital bed",
        "description":"model 1225 hospital bed",
        "attributes":{
          "EquipmentManufacturer":"Example Company",
          "SJId":"6754843090"
        }
      }
    ]
  }
}

この例では、usernamecontextオブジェクトに置き、assetsをリクエスト本文として渡します。

service.post('/mobile/custom/incidentreport/assets', function (req, res) {
  req.oracleMobile.location.assets.register(
    req.body.assets, 
    {
      username: req.body.userName, 
      mbe: req.oracleMobile.mbe.getMBE().name, 
      version: req.oracleMobile.mbe.getMBE().version
    }).then(
    function (result) {
      res.type('application/json');
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      console.dir(error);
      res.status(error.sta).send(sCode, error.error);
    }
  );
});

レスポンス本文の例を次に示します。

{
  "items": [
    {
      "id": 12,
      "createdOn": "2016-11-05T02:33:36.154Z",
      "createdBy": "anAdministrator",
      "modifiedOn": "2016-11-05T02:33:36.154Z",
      "modifiedBy": "anAdministrator",
      "name": "hospital bed #233",
      "label": "hospital bed",
      "description": "model 1225 hospital bed",
      "lastKnownLocation": null,
      "attributes": {
        "EquipmentManufacturer": "Example Company",
        "SJId": "6754843090"
      },
      "links": [
        {
          "rel": "canonical",
          "href": "/mobile/platform/location/assets/12"
        },
        {
          "rel": "self",
          "href": "/mobile/platform/location/assets/12"
        }
      ]
    }
  ]
}
location.assets.remove(id, context, httpOptions)

このメソッドを使用してアセットを削除します。

引数

id: 必須。 削除するアセットのID。 この引数は、単一の値でも、値の配列でも構いません。

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

レスポンス

単一の値を指定した場合、サービスはレスポンス本文を返しません。 アセットが削除された場合のステータス・コードは204、存在しない場合のステータス・コードは404です。

IDの配列を指定すると、リクエストが成功するとステータス・コードは200になります。 レスポンスには、個々の削除リクエストに対する一連のレスポンスを含むbatchオブジェクトが含まれています。 スキーマの詳細については、「Oracle Mobile Cloud ServiceのREST API」のDelete Multiple Assets操作を参照してください。

次に例を示します。

{
    "batch":[
        {
            "body":{
                "id":353,
                "message":"asset was deleted successfully."},
            "code":200},
        {
            "body":{
                "id":354,
                "message":"asset was deleted successfully."},
            "code":200},
        {
            "body":{
                "id":355,
                "message":"asset not found."},
            "code":404}
    ]
}

この例では、id問合せパラメータに複数のIDが含まれている場合、問合せ文字列が配列に変換されます。

MobileEnvironment_Systemロールを持つユーザーのユーザー名は、user問合せパラメータに渡されます。

service.delete('/mobile/custom/location/assets', function(req,res) {
  var contextObject = {
    username: req.query.user,
    mbe: req.oracleMobile.mbe.getMBE().name,
    version: req.oracleMobile.mbe.getMBE().version
  };
  var id = req.query.id.split(',');
  if (id.length == 0){
      id = req.query.id;
  }
  req.oracleMobile.location.assets.remove(
      id,
      contextObject
    ).then(
    function (result) {
      res.type('application/json');
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      console.dir(error);
      res.status(error.statusCode).send(error.error);
    }
  );
});
location.assets.update(id, asset, context, httpOptions)

このメソッドでは、アセットを更新できます。

引数

id: 必須。 アセットのID。 このIDは既存のアセットIDでなければなりません。

asset: Required. Oracle Mobile Cloud ServiceのREST APIPUT /mobile/system/locationManagement/assets/{id}の操作に示されているリクエスト・ルート・スキーマ(Asset)に従うJSONオブジェクトです。 次に例を示します。

{
    "lastKnownLocation":{
        "gpsPoint":{
            "latitude":37.5548,
            "longitude":-121.1566
        }
    },
    "devices":[
        11
    ]
}

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

レスポンス

更新されたアセットを示すレスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPUT /mobile/system/locationManagement/assets/{id}の操作に示されているレスポンス・ルート・スキーマ(Asset)に従うJSONオブジェクトです。

この例では、リクエスト本文は次のようになります:
{
   "userName":"anAdministrator",
   "asset":{
      "lastKnownLocation":{
         "gpsPoint":{
            "latitude":37.5548,
            "longitude":-121.1566
         }
      },
      "devices":[
         11
      ]
   }
}

この例では、usernamecontextオブジェクトに置き、assetをリクエスト本文として渡します。

service.put('/mobile/custom/incidentreport/assets/:id', function (req, res) {
  req.oracleMobile.location.assets.update(
    req.params.id,
    req.body.asset, 
    {
      username: req.body.userName, 
      mbe: req.oracleMobile.mbe.getMBE().name, 
      version: req.oracleMobile.mbe.getMBE().version
    }).then(
    function (result) {
      res.type('application/json');
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      console.dir(error);
      res.status(error.statusCode).send(error.error);
    }
  );
});    

レスポンス本文の例を次に示します。

{
  "id": 11,
  "createdOn": "2016-11-08T21:26:38.318Z",
  "createdBy": "anAdministrator",
  "modifiedOn": "2016-11-08T22:18:24.157Z",
  "modifiedBy": "anAdministrator",
  "name": "hospital bed #233",
  "label": "hospital bed",
  "description": "model 1225 hospital bed",
  "lastKnownLocation": {
    "gpsPoint": {
      "longitude": -121.1566,
      "latitude": 37.5548
    }
  },
  "devices": [
    {
      "id": 11,
      "createdOn": "2016-11-08T18:01:18.531Z",
      "createdBy": "anAdministrator",
      "modifiedOn": "2016-11-08T18:01:18.531Z",
      "modifiedBy": "anAdministrator",
      "name": "RC_WH_01_F01_B016",
      "description": "Beacon on 2nd Floor in FixitFast Warehouse in Redwood City",
      "beacon": {
        "altBeacon": {
          "id1": "B9407F30-F5F8-466E",
          "id2": "AFF9",
          "id3": "25556B57FE6D"
        }
      },
      "attributes": {
        "manufacturer": "Abc Company",
        "status": "Active",
        "manufacturerId": "10D39AE7-020E-4467-9CB2-DD36366F899D",
        "visibility": "Public"
      },
      "links": [
        {
          "rel": "canonical",
          "href": "/mobile/platform/location/devices/11"
        },
        {
          "rel": "self",
          "href": "/mobile/platform/location/devices/11"
        }
      ]
    }
  ],
  "attributes": {
    "EquipmentManufacturer": "Example Company",
    "SJId": "6754843090"
  },
  "links": [
    {
      "rel": "canonical",
      "href": "/mobile/platform/location/assets/11"
    },
    {
      "rel": "self",
      "href": "/mobile/platform/location/assets/11"
    }
  ]
}
location.devices.register(devices, context, httpOptions)

このメソッドでは、1つまたは複数のデバイスを作成できます。

引数

devices: Required. Oracle Mobile Cloud ServiceのREST APIPOST /mobile/system/locationManagement/devicesの操作に示されているリクエスト・ルート・スキーマ(Devices Array)に従うJSONオブジェクトです。 次に例を示します。

{
    "items":[
        {
            "name":"RC_WH_01_F01_B006",
            "description":"Beacon on 2nd Floor in FixitFast Warehouse in Redwood City",
            "asset":333,
            "beacon":{
                "altBeacon":{
                    "id1":"B9407F30-F5F8-466E",
                    "id2":"AFF9",
                    "id3":"25556B57FE6D"
                }
            },
            "attributes":{
                "manufacturer":"Abc Company",
                "manufacturerId":"10D39AE7-020E-4467-9CB2-DD36366F899D",
                "status":"Active",
                "visibility":"Public"
            }
        }
    ]
}

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

レスポンス

格納されたデバイスを示すレスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/system/locationManagement/devicesの操作に示されているレスポンス・ルート・スキーマ(Devices Array)に従うJSONオブジェクトです。

この例では、リクエスト本文は次のようになります:
{
  "userName":"anAdministrator",
  "devices": {
    "items":[
       {
         "name":"RC_WH_01_F01_B006",
         "description":"Beacon on 2nd Floor in FixitFast Warehouse in Redwood City",
            "beacon":{
                "altBeacon":{
                    "id1":"B9407F30-F5F8-466E",
                    "id2":"AFF9",
                    "id3":"25556B57FE6D"
                }
            },
            "attributes":{
                "manufacturer":"Abc Company",
                "manufacturerId":"10D39AE7-020E-4467-9CB2-DD36366F899D",
                "status":"Active",
                "visibility":"Public"
            }
        }
    ]
  }
}

この例では、usernameをcontextオブジェクトの中に入れ、devicesをリクエスト本文として渡しています。

service.post('/mobile/custom/incidentreport/devices, function (req, res) {
  req.oracleMobile.location.devices.register(
    req.body.devices, 
    {
      username: req.body.userName, 
      mbe: req.oracleMobile.mbe.getMBE().name, 
      version: req.oracleMobile.mbe.getMBE().version
    }).then(
    function (result) {
      res.type('application/json');
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      console.dir(error);
      res.status(error.statusCode).send(error.error);
    }
  );
});

レスポンス本文の例を次に示します。

{
  "items": [
    {
      "id": 10,
      "createdOn": "2016-11-08T15:54:51.603Z",
      "createdBy": "anAdministrator",
      "modifiedOn": "2016-11-08T15:54:51.603Z",
      "modifiedBy": "anAdministrator",
      "name": "RC_WH_01_F01_B006",
      "description": "Beacon on 2nd Floor in FixitFast Warehouse in Redwood City",
      "beacon": {
        "altBeacon": {
          "id1": "B9407F30-F5F8-466E",
          "id2": "AFF9",
          "id3": "25556B57FE6D"
        }
      },
      "attributes": {
        "manufacturer": "Abc Company",
        "manufacturerId": "10D39AE7-020E-4467-9CB2-DD36366F899D",
        "status": "Active",
        "visibility": "Public"
      },
      "links": [
        {
          "rel": "canonical",
          "href": "/mobile/platform/location/devices/10"
        },
        {
          "rel": "self",
          "href": "/mobile/platform/location/devices/10"
        }
      ]
    }
  ]
}
location.devices.remove(id, context, httpOptions)

このメソッドを使用してデバイスを削除します。

引数

id: 必須。 削除するデバイスのID。 この引数は、単一の値でも、値の配列でも構いません。

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

レスポンス

単一の値を指定した場合、サービスはレスポンス本文を返しません。 デバイスが削除された場合はステータス・コードは204、存在しない場合は404になります。

IDの配列を指定すると、リクエストが成功するとステータス・コードは200になります。 レスポンスには、個々の削除リクエストに対する一連のレスポンスを含むbatchオブジェクトが含まれています。 スキーマの詳細については、「Oracle Mobile Cloud ServiceのREST API」の複数のデバイスの削除操作を参照してください。

次に例を示します。

{
    "batch":[
        {
            "code":200,
            "body":{
                "id":121,
                "message":"device was deleted successfully."
            }
        },
        {
            "code":200,
            "body":{
                "id":122,
                "message":"device was deleted successfully."
            }
        },
        {
            "code":404,
            "body":{
                "id":123,
                "message":"device not found."
            }
        }
    ]
}

この例では、id問合せパラメータに複数のIDが含まれている場合、問合せ文字列が配列に変換されます。

MobileEnvironment_Systemロールを持つユーザーのユーザー名は、user問合せパラメータに渡されます。

service.delete('/mobile/custom/location/devices', function(req,res) {
  var contextObject = {
    username: req.query.user,
    mbe: req.oracleMobile.mbe.getMBE().name,
    version: req.oracleMobile.mbe.getMBE().version
  };
  var id = req.query.id.split(',');
  if (id.length == 0){
      id = req.query.id;
  }
  req.oracleMobile.location.devices.remove(
      id,
      contextObject
    ).then(
    function (result) {
      res.type('application/json');
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      console.dir(error);
      res.status(error.statusCode).send(error.error);
    }
  );
});
location.devices.update(id, device, context, httpOptions)

このメソッドを使用すると、デバイスを更新できます。

引数

id: 必須。 デバイスのID。 このIDは既存のデバイスIDでなければなりません。

device: Required. Oracle Mobile Cloud ServiceのREST APIPUT /mobile/system/locationManagement/device/{id}の操作に示されているリクエスト・ルート・スキーマ(Device)に従うJSONオブジェクトです。 次に例を示します。

{
    "attributes":{
        "status":"Inactive",
        "visibility":"Private"
    }
}

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

レスポンス

更新されたデバイスを示すレスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPUT /mobile/system/locationManagement/devices/{id}の操作に示されているレスポンス・ルート・スキーマ(Device)に従うJSONオブジェクトです。

この例では、リクエスト本文は次のようになります:
{
   "userName":"anAdministrator",
   "device":{
      "attributes":{
         "status":"Inactive",
         "visibility":"Private"
      }
   }
}

この例では、usernamecontextオブジェクトに置き、deviceをリクエスト本文として渡します。

service.put('/mobile/custom/incidentreport/device/:id', function (req, res) {
  req.oracleMobile.location.device.update(
    req.params.id,
    req.body.device, 
    {
      username: req.body.userName, 
      mbe: req.oracleMobile.mbe.getMBE().name, 
      version: req.oracleMobile.mbe.getMBE().version
    }).then(
    function (result) {
      res.type('application/json');
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      console.dir(error);
      res.status(error.statusCode).send(error.error);
    }
  );
});    

レスポンス本文の例を次に示します。

{
  "id": 11,
  "createdOn": "2016-11-08T18:01:18.531Z",
  "createdBy": "anAdministrator",
  "modifiedOn": "2016-11-08T22:45:47.545Z",
  "modifiedBy": "anAdministrator",
  "name": "RC_WH_01_F01_B016",
  "description": "Beacon on 2nd Floor in FixitFast Warehouse in Redwood City",
  "asset": {
    "id": 11,
    "createdOn": "2016-11-08T21:26:38.318Z",
    "createdBy": "anAdministrator",
    "modifiedOn": "2016-11-08T22:18:24.157Z",
    "modifiedBy": "anAdministrator",
    "name": "hospital bed #233",
    "label": "hospital bed",
    "description": "model 1225 hospital bed",
    "lastKnownLocation": {
      "gpsPoint": {
        "longitude": -121.1566,
        "latitude": 37.5548
      }
    },
    "attributes": {
      "EquipmentManufacturer": "Example Company",
      "SJId": "6754843090"
    },
    "links": [
      {
        "rel": "canonical",
        "href": "/mobile/platform/location/assets/11"
      },
      {
        "rel": "self",
        "href": "/mobile/platform/location/assets/11"
      }
    ]
  },
  "beacon": {
    "altBeacon": {
      "id1": "B9407F30-F5F8-466E",
      "id2": "AFF9",
      "id3": "25556B57FE6D"
    }
  },
  "attributes": {
    "manufacturer": "Abc Company",
    "status": "Inactive",
    "manufacturerId": "10D39AE7-020E-4467-9CB2-DD36366F899D",
    "visibility": "Private"
  },
  "links": [
    {
      "rel": "canonical",
      "href": "/mobile/platform/location/devices/11"
    },
    {
      "rel": "self",
      "href": "/mobile/platform/location/devices/11"
    }
  ]
}
location.places.register(places, context, httpOptions)

このメソッドを使用すると、1つ以上の場所を作成できます。

引数

places: 必須。 Oracle Mobile Cloud ServiceのREST APIPOST /mobile/system/locationManagement/placesの操作に示されているリクエスト・ルート・スキーマ(Places Array)に従うJSONオブジェクトです。 次に例を示します。

{
    "items":[
        {
            "name":"FixItFast Redwood City Warehouse",
            "label":"FixItFast Warehouse",
            "parentPlace":42,
            "description":"FixItFast Warehouse in Redwood City",
            "address":{
                "gpsPoint":{
                    "latitude":122,
                    "longitude":37
                }
            },
            "devices":[
                12345
            ],
            "attributes":{
                "hours":"9am-6pm"
            }
        }
    ]
}

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

レスポンス

格納された場所を示すレスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/system/locationManagement/placesの操作に示されているレスポンス・ルート・スキーマ(Places Array)に従うJSONオブジェクトです。

この例では、リクエスト本文は次のようになります:
{
  "userName":"anAdministrator",
  "places": {
    "items":[
       {
            "name":"FixItFast Redwood City Warehouse",
            "label":"FixItFast Warehouse",
            "description":"FixItFast Warehouse in Redwood City",
            "address":{
                "gpsPoint":{
                    "latitude":89,
                    "longitude":37
                }
            },
                "attributes":{
                "hours":"9am-6pm"
            }
        }
    ]
  }
}

この例では、usernamecontextオブジェクトに置き、placesをリクエスト本文として渡します。

service.post('/mobile/custom/incidentreport/places', function (req, res) {
  req.oracleMobile.location.places.register(
    req.body.places, 
    {
      username: req.body.userName, 
      mbe: req.oracleMobile.mbe.getMBE().name, 
      version: req.oracleMobile.mbe.getMBE().version
    }).then(
    function (result) {
      res.type('application/json');
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      console.dir(error);
      res.status(error.statusCode).send(error.error);
    }
  );
});

レスポンス本文の例を次に示します。

{
  "items": [
    {
      "id": 10,
      "createdOn": "2016-11-08T17:55:21.816Z",
      "createdBy": "john.doe",
      "modifiedOn": "2016-11-08T17:55:21.816Z",
      "modifiedBy": "john.doe",
      "name": "FixItFast Redwood City Warehouse",
      "label": "FixItFast Warehouse",
      "description": "FixItFast Warehouse in Redwood City",
      "hasChildren": false,
      "address": {
        "gpsPoint": {
          "longitude": 37,
          "latitude": 89
        }
      },
      "attributes": {
        "hours": "9am-6pm"
      },
      "links": [
        {
          "rel": "canonical",
          "href": "/mobile/platform/location/places/10"
        },
        {
          "rel": "self",
          "href": "/mobile/platform/location/places/10"
        }
      ]
    }
  ]
}
location.places.remove(id, context, httpOptions)

場所を削除するには、このメソッドを使用します。

引数

id: 必須。 削除する場所のID。 この引数は、単一の値でも、値の配列でも構いません。

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

レスポンス

単一の値を指定した場合、サービスはレスポンス本文を返しません。 場所が削除された場合はステータス・コードは204、存在しない場合は404になります。

IDの配列を指定すると、リクエストが成功するとステータス・コードは200になります。 レスポンスには、個々の削除リクエストに対する一連のレスポンスを含むbatchオブジェクトが含まれています。 スキーマの詳細は、「Oracle Mobile Cloud ServiceのREST API」の複数の場所の削除操作を参照してください。

次に例を示します。

{
    "batch":[
        {
            "body":{
                "id":222,
                "message":"place was deleted successfully."},
            "code":200},
        {
            "body":{
                "id":223,
                "message":"place was deleted successfully."},
            "code":200},
        {
            "body":{
                "id":224,
                "message":"place not found."},
            "code":404}
    ]
}

この例では、id問合せパラメータに複数のIDが含まれている場合、問合せ文字列が配列に変換されます。

MobileEnvironment_Systemロールを持つユーザーのユーザー名は、user問合せパラメータに渡されます。

service.delete('/mobile/custom/location/places, function(req,res) {
  var contextObject = {
    username: req.query.user,
    mbe: req.oracleMobile.mbe.getMBE().name,
    version: req.oracleMobile.mbe.getMBE().version
  };
  var id = req.query.id.split(',');
  if (id.length == 0){
      id = req.query.id;
  }
  req.oracleMobile.location.places.remove(
      id,
      contextObject
    ).then(
    function (result) {
      res.type('application/json');
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      console.dir(error);
      res.status(error.statusCode).send(error.error);
    }
  );
});
location.places.removeCascade(id, context, httpOptions)

親の場所とそのすべての子の場所を削除するには、このメソッドを使用します。

引数

id: 必須。 場所のID。 このIDは既存のプレースIDである必要があります。

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

この例では、cascade問合せパラメータがtrueの場合、このメソッドはremove()ではなくremoveCascade()を呼び出します。

MobileEnvironment_Systemロールを持つユーザーのユーザー名は、user問合せパラメータに渡されます。

service.delete('/mobile/custom/location/places/:id', function(req,res) {
  var contextObject = {
    username: req.query.user,
    mbe: req.oracleMobile.mbe.getMBE().name,
    version: req.oracleMobile.mbe.getMBE().version
  };
  var removeFunc = req.oracleMobile.location.places.remove;
  if (req.query.cascade == 'true') {
      removeFunc = req.oracleMobile.location.places.removeCascade;
  }
  removeFunc(
    req.params.id,
    contextObject
  ).then(
     function (result) {
        res.type('application/json');
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        console.dir(error);
        res.status(error.statusCode).send(error.error);
      }
   )
 });
location.places.update(id, place, context, httpOptions)

このメソッドを使用すると、場所を更新できます。

引数

id: 必須。 場所のID。 このIDは既存のプレースIDである必要があります。

place: Required. REST APIs for Oracle Mobile Cloud ServicePUT /mobile/system/locationManagement/place/{id}の操作に示されているリクエスト・ルート・スキーマ(Place)に従うJSONオブジェクトです。 次に例を示します。

{
    "address":{
        "gpsPoint":{
            "latitude":-121.1566,
            "longitude":37.5548
        }
    },
    "devices":[
        1111
    ]
}

context: Required. 「ロケーション管理コンテキスト引数」で説明されているJSONオブジェクト。

レスポンス

更新された場所を示すレスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPUT /mobile/system/locationManagement/places/{id}の操作に示されているレスポンス・ルート・スキーマ(Place)に従うJSONオブジェクトです。

この例では、リクエスト本文は次のようになります:
{
   "userName":"anAdministrator",
   "place":{
      "address":{
         "gpsPoint":{
            "latitude":-89,
            "longitude":37
         }
      },
      "devices":[
         11
      ]
   }
}

この例では、usernamecontextオブジェクトに置き、placeをリクエスト本文として渡します。

service.put('/mobile/custom/incidentreport/place/:id', function (req, res) {
  req.oracleMobile.location.place.update(
    req.params.id,
    req.body.place, 
    {
      username: req.body.userName, 
      mbe: req.oracleMobile.mbe.getMBE().name, 
      version: req.oracleMobile.mbe.getMBE().version
    }).then(
    function (result) {
      res.type('application/json');
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      console.dir(error);
      res.status(error.statusCode).send(error.error);
    }
  );
});    

レスポンス本文の例を次に示します。

{
  "id": 11,
  "createdOn": "2016-11-08T23:36:55.371Z",
  "createdBy": "anAdministrator",
  "modifiedOn": "2016-11-08T23:37:45.576Z",
  "modifiedBy": "anAdministrator",
  "name": "FixItFast Redwood City Warehouse",
  "label": "FixItFast Warehouse",
  "description": "FixItFast Warehouse in Redwood City",
  "hasChildren": false,
  "address": {
    "gpsPoint": {
      "longitude": 37,
      "latitude": 89
    }
  },
  "devices": [
    {
      "id": 11,
      "createdOn": "2016-11-08T18:01:18.531Z",
      "createdBy": "anAdministrator",
      "modifiedOn": "2016-11-08T22:45:47.545Z",
      "modifiedBy": "anAdministrator",
      "name": "RC_WH_01_F01_B016",
      "description": "Beacon on 2nd Floor in FixitFast Warehouse in Redwood City",
      "beacon": {
        "altBeacon": {
          "id1": "B9407F30-F5F8-466E",
          "id2": "AFF9",
          "id3": "25556B57FE6D"
        }
      },
      "attributes": {
        "manufacturer": "Abc Company",
        "status": "Inactive",
        "manufacturerId": "10D39AE7-020E-4467-9CB2-DD36366F899D",
        "visibility": "Private"
      },
      "links": [
        {
          "rel": "canonical",
          "href": "/mobile/platform/location/devices/11"
        },
        {
          "rel": "self",
          "href": "/mobile/platform/location/devices/11"
        }
      ]
    }
  ],
  "attributes": {
    "hours": "9am-6pm"
  },
  "links": [
    {
      "rel": "canonical",
      "href": "/mobile/platform/location/places/11"
    },
    {
      "rel": "self",
      "href": "/mobile/platform/location/places/11"
    }
  ]
}

カスタム・コードから通知APIにアクセス

通知APIを使用して、予定されているイベントやユーザーが興味を持っている可能性のあるニュースに関するアラートなど、モバイル・アプリ・ユーザーにメッセージを送信できます。 デバイス、ユーザー、オペレーティング・システムなどのメッセージのターゲットを指定することができ、メッセージのスケジュールを設定できます。 また、通知について問い合わせることも、送信されていないスケジュール通知を削除することもできます。

通知を使用する方法の詳細については、「通知」を参照してください。

このAPIには、次のメソッドがあります:

通知コンテキスト引数

すべての通知APIメソッドには、context引数が必要です。これは、次のプロパティを持つJSONオブジェクトです。 この情報は、通知を送信および表示するための承認を得るために必要です。

カスタム・コードは、この情報を取得するためにmbe.getMBE()を呼び出すことができます。

プロパティ 説明 タイプ
mbe 通知に関連付けられているモバイル・バックエンドの名前。 文字列
mbeId (オプション)通知に関連付けられているモバイル・バックエンドのID。 省略した場合、デフォルトはモバイル・アプリケーションが使用しているモバイル・バックエンドIDです。 文字列
version モバイル・バックエンドのバージョン。 文字列
notification.getAll(context, options, httpOptions)

このメソッドを使用すると、条件に一致する通知を取得できます。 すべての基準に一致する通知のみが返されます。

引数

context: Required. 「通知コンテキスト引数」で説明されているJSONオブジェクト。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているプロパティに加えて、これらのプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
createdOnOrAfter 基準: 指定されたUTCの日付/時間(YYYY-DD-MM[Thh:mm]Z形式)以降のcreatedOnによるフィルタリング。 文字列 なし
createdOnOrBefore 基準: 指定されたUTCの日付/時間(YYYY-DD-MM[Thh:mm]Z形式)またはその前のcreatedOnでフィルタリングします。 文字列 なし
limit 返されるアイテムの最大数。 リクエストされた制限が大きすぎる場合は、下限が代入されます。 整数 なし
offset 返される最初のアイテムの0から始まるインデックスです。 整数 なし
orderBy 問合せ操作の順序を指定します。 デフォルトのソート順はIDで昇順です。 形式は次のとおりです: attrパラメータは、idstatustagplatformsendOncreatedOn、またはprocessedOnであってもよく、ここで、"orderBy" "=" 1#(attr [":" asc "|" desc "])。 文字列 なし
processedOnOrAfter 基準: 指定されたUTCの日付/時間(YYYY-DD-MM[Thh:mm]Z形式)以降のprocessedOnによるフィルタリング。 文字列 なし
processedOnOrBefore 基準: 指定されたUTCの日付/時間(YYYY-DD-MM[Thh:mm]Z形式)またはその前のprocessedOnでフィルタリングします。 文字列 なし
q この文字列と大文字と小文字を区別しない部分一致に基づいて結果をフィルタリングします。 たとえば、q=marketは、tagMarketingmarketing、およびmarketsに等しい通知を返します。 文字列 なし
sendOnOrAfter 基準: 指定されたUTCの日付/時間(YYYY-DD-MM[Thh:mm]Z形式)以降のsendOnによるフィルタリング。 文字列 なし
sendOnOrBefore 基準: 指定されたUTCの日付/時間(YYYY-DD-MM[Thh:mm]Z形式)またはその前のsendOnでフィルタリングします。 文字列 なし
status 基準: ステータスでフィルタリング 文字列 なし
tag 基準: タグで絞り込む 文字列 なし

レスポンス

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIGET /mobile/system/notifications/notifications操作に示されているnotificationPagingスキーマに従うJSONオブジェクトです。

このメソッドを呼び出す例を次に示します:

service.get('/mobile/custom/incidentreport/notifications',
  function (req, res) {
    req.oracleMobile.notification.getAll({
      mbe: req.oracleMobile.mbe.getMBE().name,
      version: req.oracleMobile.mbe.getMBE().version})
    .then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

レスポンス本文の例を次に示します。

{
  "items": [
    {
      "id": 2,
      "message": "Incident Updated: Broken Dryer",
      "users": [
        "J Doe"
      ],
      "roles": [],
      "notificationTokens": [],
      "status": "New",
      "createdOn": "2015-09-24T21:58:04.465Z",
      "links": [
        {
          "rel": "canonical",
          "href": "/mobile/system/notifications/notifications/2"
        },
        {
          "rel": "self",
          "href": "/mobile/system/notifications/notifications/2"
        }
      ]
    },
    {
      "id": 3,
      "message": "Incident Updated: Malfunctioning Air Conditioner",
      "users": [
        "Lynn Smith"
      ],
      "roles": [],
      "notificationTokens": [],
      "status": "New",
      "createdOn": "2015-09-24T21:58:07.413Z",
      "links": [
        {
          "rel": "canonical",
          "href": "/mobile/system/notifications/notifications/3"
        },
        {
          "rel": "self",
          "href": "/mobile/system/notifications/notifications/3"
        }
      ]
    }
  ],
  "hasMore": false,
  "limit": 2,
  "count": 2,
  "links": [
    {
      "rel": "canonical",
      "href": "/mobile/system/notifications/notifications/?offset=0&limit=2"
    },
    {
      "rel": "self",
      "href": "/mobile/system/notifications/notifications/"
    }
  ]
}
notification.getById(id, context, options, httpOptions)

このメソッドを使用すると、特定の通知をIDで取得できます。

引数

id: 必須。 文字列または整数。 生成された通知ID。

context: Required. 「通知コンテキスト引数」で説明されているJSONオブジェクト。

options: 任意。 「共通オプション引数のプロパティ」で説明されているJSONオブジェクト。

レスポンス

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIGET /mobile/system/notifications/notifications/{id}操作に示されているnotificationスキーマに従うJSONオブジェクトです。

通知を受け取るメソッドを呼び出す例を次に示します:

service.get('/mobile/custom/incidentreport/notifications/:id',
  function (req, res) {    
    req.oracleMobile.notification.getById(req.params.id, {
        mbe: req.oracleMobile.mbe.getMBE().name,
        version: req.oracleMobile.mbe.getMBE().version})
    .then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

レスポンス本文の例を次に示します。

{
  "id": 1,
  "message": "Incident Updated: Leaky Faucet",
  "users": [
    "Lynn Smith"
  ],
  "roles": [],
  "notificationTokens": [],
  "status": "New",
  "createdOn": "2015-09-24T21:44:45.708Z",
  "links": [
    {
      "rel": "canonical",
      "href": "/mobile/system/notifications/notifications/1"
    },
    {
      "rel": "self",
      "href": "/mobile/system/notifications/notifications/1"
    }
  ]
}
notification.post(notification, context, options, httpOptions)

このメソッドを使用すると、通知を作成できます。

引数

notification: Required. Oracle Mobile Cloud ServiceのREST APIPOST /mobile/system/notifications/notifications操作に示されているnotificationCreateスキーマに従うJSONオブジェクト。 次に例を示します。

{
    message:'This is the alert message.',
    tag:'Marketing',
    notificationTokens:['APNSdeviceToken']
}

context: Required. 「通知コンテキスト引数」で説明されているJSONオブジェクト。

options: 任意。 「共通オプション引数のプロパティ」で説明されているJSONオブジェクト。

レスポンス

戻り値には次のヘッダーが含まれます:

ヘッダー 説明 タイプ
Location 通知の標準リソースURI。 文字列

レスポンス本文は、保存された通知を示し、POST /mobile/system/notifications/notifications操作のために「Oracle Mobile Cloud ServiceのREST API」で表示されるnotificationスキーマに従うJSONオブジェクトです。

通知を送信するこの例では、リクエスト本文は次のようになります: {incidentName: 'Leaky Faucet', customerName: 'Lynn Smith'}

service.post('/mobile/custom/incidentreport/notifications',
  function (req, res) {
    var notification = {
      sendOn: '2016-06-25T6:00Z',
      message: 'Incident Updated: ' +
      req.body.incidentName,
      users: [req.body.customerName]
    };   
    req.oracleMobile.notification.post(notification, {
        mbe: req.oracleMobile.mbe.getMBE().name,
        version: req.oracleMobile.mbe.getMBE().version})
    .then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

レスポンス本文の例を次に示します。

{
  "id": 1,
  "message": "Incident Updated: Leaky Faucet",
  "users": [
    "Lynn Smith"
  ],
  "roles": [],
  "notificationTokens": [],
  "sendOn": "2016-06-25T06:00Z",
  "status": "New",
  "createdOn": "2015-06-24T21:44:45.708Z",
  "links": [
    {
      "rel": "canonical",
      "href": "/mobile/system/notifications/notifications/1"
    },
    {
      "rel": "self",
      "href": "/mobile/system/notifications/notifications/1"
    }
  ]
}
notification.remove(id, context, options, httpOptions)

このメソッドを使用すると、通知を削除できます。 ステータスがScheduledの場合にのみ通知を削除できます。

引数

id: 必須。 文字列または整数。 生成された通知ID。

context: Required. 「通知コンテキスト引数」で説明されているJSONオブジェクト。

options: 任意。 「共通オプション引数のプロパティ」で説明されているJSONオブジェクト。

このメソッドを呼び出す例を次に示します:

service.delete('/mobile/custom/incidentreport/notifications/:id',
  function (req, res) {
    req.oracleMobile.notification.remove(req.params.id, {
        mbe: req.oracleMobile.mbe.getMBE().name,
        version: req.oracleMobile.mbe.getMBE().version})
    .then(      
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  });

カスタム・コードからのストレージAPIへのアクセス

Storage APIを使用すると、モバイル・アプリケーション・オブジェクトをクラウドに格納できます。 オブジェクトには、テキスト、JSON、イメージなどのバイナリ・オブジェクトを使用できます。 これらのオブジェクトはコレクションごとにグループ化されます。 コレクションとオブジェクトについては、「ストレージ」を参照してください。

このAPIには、次のメソッドがあります:

storage.doesCollectionExist(collectionId, options, httpOptions)

このメソッドを使用して、コレクションが存在するかどうかを判断できます。 コレクションを使用して、コレクションがETagに一致する(または一致しない)かどうかを確認することもできます。

引数

collectionId: 必須。 文字列。 コレクションの名前。 コレクションのメタデータを見ると、この値はメタデータのid値に対応します。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているプロパティに加えて、これらのプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
encodeURI trueに設定すると、collectionIdの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
ifMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致する場合にのみ、trueが返されます。 文字列 なし
ifNoneMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致しない場合にのみ、trueが返されます。 文字列 なし

レスポンス

このメソッドはブール値を返します。

次の例では、このメソッドを使用してコレクションがオブジェクトを格納する前に存在することを確認します。

req.oracleMobile.storage.doesCollectionExist('attachments').then(
  function(result){
    if (result) {
      req.oracleMobile.storage.store('attachments', {id: 'incident412-pic'}, {inType: 'json'}).then(
        function (result) {
          res.status(result.statusCode).send(result.result);
        },
        function (error) {
          res.status(error.statusCode).send(error.error);
        }
      );
    } else {
      res.status(404).send('Storage has not been configured for this app. Please contact your admin.');
    };
  },
  function(error){
    res.status(error.statusCode).send(error.error);
  }
);        
storage.doesExist(collectionId, objectId, options, httpOptions)

このメソッドを使用して、オブジェクトが存在するかどうかを判断できます。 このオブジェクトを使用して、オブジェクトがETagと一致するかどうか、または指定された日付の後に変更されたかどうかを確認することもできます。

引数

collectionId: 必須。 文字列。 コレクションの名前。 コレクションのメタデータを見ると、この値はメタデータのid値に対応します。

objectId: 必須。 文字列。 アクセスされているオブジェクト。 オブジェクトがstorage.storeById()メソッドを使用して格納されていた場合、これはid引数として提供されたIDであり、オブジェクトがstorage.store()メソッドを使用して格納されていればIDが生成されました。 オブジェクトのメタデータを見ると、この引数の値はメタデータのid属性に対応します。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているプロパティに加えて、これらのプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
contentDisposition このプロパティを使用すると、Content-Dispositionレスポンス・ヘッダーの値を指定できます。 文字列 なし
encodeURI trueに設定すると、collectionIdobjectId、およびuserの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
ifMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致する場合にのみ、呼び出しは正常に完了します。 文字列 なし
ifModifiedSince HTTP-date形式の日付と時間。 たとえば、Mon, 30 Jun 2014 19:43:31 GMTです。 このプロパティで指定された日付以降にオブジェクトが変更された場合にのみ、リクエストは正常に完了します。 このプロパティを使用すると、データが変更されていない場合にデータを再取得しないことによって転送されるデータの量を減らすことができます。 日付 なし
ifNoneMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致しない場合にのみ、呼び出しは正常に完了します。 このプロパティを使用すると、データが変更されていない場合にデータを再取得しないことによって転送されるデータの量を減らすことができます。 文字列 なし
ifUnmodifiedSince HTTP-date形式の日付と時間。 たとえば、Mon, 30 Jun 2014 19:43:31 GMTです。 このプロパティで指定された日付以降にオブジェクトが変更されなかった場合にのみ、リクエストは正常に完了します。 日付 なし
user これはユーザーのID (ユーザー名ではない)です。 この問合せパラメータを使用すると、READ_ALL/READ_WRITE_ALL権限を持つユーザーは、別のユーザー隔離領域にアクセスできます。 READ/READ_WRITE権限を持つユーザーは、自分のスペースにのみアクセスできます。 文字列 共有コレクションについて問い合わせる場合、デフォルトはありません。

隔離されたコレクションについて問い合わせていて、READ_ALL/READ_WRITE_ALLパーミッションがある場合、このプロパティを含めない限り、サインインされたユーザーが引き継がれます。 隔離されたコレクションに対してREAD_ALL/READ_WRITE_ALLパーミッションがある場合は、このプロパティを組み込んで、別のユーザーのスペースにあるオブジェクトについて照会する必要があります。

レスポンス

このメソッドはブール値を返します。

この例では、コードはdoesExistを呼び出して、格納されたオブジェクトが最後に取得されたときと同じETag ("1")を持っているかどうかを確認します。

req.oracleMobile.storage.doesExist('attachments', 'incident412-pic', {ifMatch: '\"' + 1 + '\"'}).then(
  function (result) {
    res.status(200).send('Object has not changed.');
  },
  function (error) {
    res.status(412).send('Object was modified by someone else.');
  }
) 
storage.getAll(collectionId, options, httpOptions)

このメソッドは、コレクション内のすべてのオブジェクトのメタデータを返します。

引数

collectionId: 必須。 文字列。 コレクションの名前。 コレクションのメタデータを見ると、この値はメタデータのid値に対応します。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているプロパティに加えて、これらのプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
encodeURI trueに設定すると、collectionIdorderBy、およびuserの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
limit 返されるアイテムの最大数。 リクエストされた制限が100より大きい場合は、代わりに100が使用されます。 整数 なし
offset 返される最初のアイテムの0から始まるインデックスです。 整数 なし
orderBy このプロパティを使用して、結果をnamemodifiedBymodifiedOncreatedBycreatedOn、またはcontentLengthでソートします。 :ascまたは:descを追加して、昇順または降順のどちらでソートするかを指定できます。 たとえば、modifiedOn:descです。 文字列 なし
q 返されるアイテムは、アイテムのidnamecreatedByまたはmodifiedByプロパティの大文字小文字を区別しない部分一致に基づいています。 たとえば、このプロパティをsamに設定すると、idaxsam3createdBySAMANTHAのオブジェクトが返されます。 文字列 なし
sync このプロパティが存在し、値がtrueの場合、戻り値には、同期ライブラリがオフラインで使用するためにローカルにデータをキャッシュするために必要な情報が含まれます。 この値は、Oracle-Mobile-Sync-Agentリクエスト・ヘッダーから取得できます(存在する場合)。 Boolean false
totalResults このプロパティの値がtrueの場合、レスポンス本文には、コレクション内のアイテムの合計数を表す値とともにtotalResults属性が含まれます。 デフォルトでは、レスポンスにはこの値は含まれません。 Boolean false
user これはユーザーのID (ユーザー名ではない)です。 すべてのユーザーを取得するには、* (ワイルドカード)を使用します。 この問合せパラメータを使用すると、READ_ALL/READ_WRITE_ALL権限を持つユーザーは、別のユーザー隔離領域にアクセスできます。 READ/READ_WRITE権限を持つユーザーは、自分のスペースにのみアクセスできます。 文字列 共有コレクションについて問い合わせる場合、デフォルトはありません。

隔離されたコレクションについて問い合わせていて、READ_ALL/READ_WRITE_ALLパーミッションがある場合、このプロパティを含めない限り、サインインされたユーザーが引き継がれます。 隔離されたコレクションに対してREAD_ALL/READ_WRITE_ALLパーミッションがある場合は、このプロパティを組み込んで、別のユーザーのスペースにあるオブジェクトについて照会する必要があります。

レスポンス

戻り値には、次のヘッダーが含まれます:

ヘッダー 説明 タイプ
Cache-Control 結果をキャッシュする方法を説明します。 文字列
Oracle-Mobile-Sync-Resource-Type 同期ライブラリはこのヘッダーを使用します。 文字列

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIGET /mobile/platform/storage/collections/{collection}/objects操作に示されているレスポンス本文スキーマに従うJSONオブジェクトです。

次に、このメソッドを呼び出す例を示します。 レスポンスは、変更された日付順にオブジェクトを降順で表示します。 syncプロパティがtrueに設定されているため、クライアント・アプリケーションはレスポンスをキャッシュできます。

// Get metadata about the objects in the attachments collection.
// List most recently modified first.
service.get('/mobile/custom/incidentreport/attachments',
  function (req, res) {
    req.oracleMobile.storage.getAll('attachments', 
    {orderBy: 'modifiedOn:desc', sync: true}).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  }); 

レスポンス本文の例を次に示します:

{
    "items":[
        {
            "eTag":"\"2\"",
            "id":"incident412-pic",
            "createdBy":"jdoe",
            "name":"Incident Picture",
            "createdOn":"2014-11-20T19:57:04Z",
            "modifiedOn":"2014-11-20T19:58:09Z",
            "modifiedBy":"jdoe",
            "links":[
                {
                    "rel":"canonical",
                    "href":"/mobile/platform/storage/collections/attachments/objects/profile-pic"
                },
                {
                    "rel":"self",
                    "href":"/mobile/platform/storage/collections/attachments/objects/profile-pic"
                }
            ],
            "contentType":"image/png",
            "contentLength":937647
        },
        {
            "eTag":"\"1\"",
            "id":"incident131-pic",
            "createdBy":"jsmith",
            "name":"Incident Picture",
            "createdOn":"2014-11-20T18:27:02Z",
            "modifiedOn":"2014-11-20T18:27:02Z",
            "modifiedBy":"jsmith",
            "links":[
                {
                    "rel":"canonical",
                    "href":"/mobile/platform/storage/collections/attachments/objects/0683d48b-fdc5-4397-8ca2-824e2b0cae65"
                },
                {
                    "rel":"self",
                    "href":"/mobile/platform/storage/collections/attachments/objects/0683d48b-fdc5-4397-8ca2-824e2b0cae65"
                }
            ],
            "contentType":"image/jpeg",
            "contentLength":5266432
        }
    ],
    "hasMore":true,
    "limit":2,
    "offset":4,
    "count":2,
    "totalResults":7,
    "links":[
        {
            "rel":"canonical",
            "href":"/mobile/platform/storage/collections/attachments/objects/"
        },
        {
            "rel":"self",
            "href":"/mobile/platform/storage/collections/attachments/objects?offset=4&limit=2&orderBy=name:asc&totalResults=true"
        },
        {
            "rel":"prev",
            "href":"/mobile/platform/storage/collections/attachments/objects?offset=2&limit=2&orderBy=name:asc&totalResults=true"
        },
        {
            "rel":"next",
            "href":"/mobile/platform/storage/collections/attachments/objects?offset=6&limit=2&orderBy=name:asc&totalResults=true"
        }
    ]
}
storage.getById(collectionId, objectId, options, httpOptions)

このメソッドは、オブジェクト識別子に基づいてコレクションからオブジェクトとそのメタデータを取得します。

引数

collectionId: 必須。 文字列。 コレクションの名前。 コレクションのメタデータを見ると、この値はメタデータのid値に対応します。

objectId: 必須。 文字列。 アクセスされているオブジェクト。 オブジェクトがstorage.storeById()メソッドを使用して格納されていた場合、これはid引数として提供されたIDであり、オブジェクトがstorage.store()メソッドを使用して格納されていればIDが生成されました。 オブジェクトのメタデータを見ると、この引数の値はメタデータのid属性に対応します。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているプロパティに加えて、これらのプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
contentDisposition このプロパティを使用すると、Content-Dispositionレスポンス・ヘッダーの値を指定できます。 文字列 なし
encodeURI trueに設定すると、collectionIdobjectId、およびuserの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
ifMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致する場合にのみ、呼び出しは正常に完了します。 文字列 なし
ifModifiedSince HTTP-date形式の日付と時間。 たとえば、Mon, 30 Jun 2014 19:43:31 GMTです。 このプロパティで指定された日付以降にオブジェクトが変更された場合にのみ、リクエストは正常に完了します。 このプロパティを使用すると、データが変更されていない場合にデータを再取得しないことによって転送されるデータの量を減らすことができます。 日付 なし
ifNoneMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致しない場合にのみ、呼び出しは正常に完了します。 このプロパティを使用すると、データが変更されていない場合にデータを再取得しないことによって転送されるデータの量を減らすことができます。 文字列 なし
ifUnmodifiedSince HTTP-date形式の日付と時間。 たとえば、Mon, 30 Jun 2014 19:43:31 GMTです。 このプロパティで指定された日付以降にオブジェクトが変更されなかった場合にのみ、リクエストは正常に完了します。 日付 なし
range このプロパティを使用すると、バイトのサブセットをリクエストできます。 たとえば、bytes=0-99は最初の100バイトを取得します。 文字列 なし
sync このプロパティが存在し、値がtrueの場合、戻り値には、同期ライブラリがオフラインで使用するためにローカルにデータをキャッシュするために必要な情報が含まれます。 この値は、Oracle-Mobile-Sync-Agentリクエスト・ヘッダーから取得できます(存在する場合)。 Boolean false
user これはユーザーのID (ユーザー名ではない)です。 この問合せパラメータを使用すると、READ_ALL/READ_WRITE_ALL権限を持つユーザーは、別のユーザー隔離領域にアクセスできます。 READ/READ_WRITE権限を持つユーザーは、自分のスペースにのみアクセスできます。 文字列 共有コレクションについて問い合わせる場合、デフォルトはありません。

隔離されたコレクションについて問い合わせていて、READ_ALL/READ_WRITE_ALLパーミッションがある場合、このプロパティを含めない限り、サインインされたユーザーが引き継がれます。 隔離されたコレクションのREAD_ALL/READ_WRITE_ALLアクセス権を持っている場合は、別のユーザーのスペースからオブジェクトを取得するためにこのプロパティを含める必要があります。

レスポンス

戻り値には、次のヘッダーが含まれます:

ヘッダー 説明 タイプ
Accept-Ranges このヘッダーは、オブジェクト・リソースをリクエストするときにバイト範囲が提供されることを示します。 文字列
Cache-Control 結果をキャッシュする方法を説明します。 文字列
Content-Disposition このレスポンス・ヘッダーは、options引数にcontentDispositionプロパティが含まれている場合に返されます。 レスポンス・ヘッダーの値は、プロパティの値と同じです。 文字列
Content-Length バイト単位のオブジェクトのサイズ。 数値
Content-Type オブジェクトのメディア・タイプ(image/jpegなど)。 文字列
Etag 各アイテムにはETag値があります。 この値は、アイテムが更新されるたびに変更されます。 値には、開始および終了の二重引用符(たとえば、"2")が含まれます。 文字列
Last-Modified リソースが最後に変更された日時。 この日付はRFC-1123形式です。 たとえば、Fri, 29 Aug 2014 12:34:56 GMTです。 日付
Oracle-Mobile-Canonical-Link このオブジェクトを一意に参照するために使用できる相対URI。 文字列
Oracle-Mobile-Created-By オブジェクトを作成したユーザーのユーザー名。 文字列
Oracle-Mobile-Created-On オブジェクトが作成されたときのISO 8601形式の日付と時間(例:2014-06-30T01:02:03Z)。 文字列
Oracle-Mobile-Modified-By オブジェクトを最後に変更したユーザーのユーザー名。 文字列
Oracle-Mobile-Modified-On オブジェクトが最後に変更されたときの日付と時間。ISO 8601形式(例:2014-06-30T01:02:03Z)。 文字列
Oracle-Mobile-Name オブジェクトの表示名。 文字列
Oracle-Mobile-Self-Link 指定された分離レベル内でこのオブジェクトを一意に参照するために使用できる相対URI。 文字列
Oracle-Mobile-Sync-Expires このヘッダーは、同期ライブラリによって使用されます。 文字列
Oracle-Mobile-Sync-No-Store このヘッダーは、同期ライブラリによって使用されます。 Boolean

レスポンス本文は格納されたオブジェクトです。

次に、このメソッドを呼び出す例を示します。 syncプロパティがtrueに設定されているため、クライアント・アプリケーションはレスポンスをキャッシュできます。

req.oracleMobile.storage.getById('attachments', 'incident412-notes', {sync: true}).then(
  function (result) {
    res.status(result.statusCode).send(result.result);
  },
  function (error) {
    res.status(error.statusCode).send(error.error);
  }
); 
storage.getCollection(collectionId, options, httpOptions)

このメソッドは、特定のコレクションに関するメタデータを返します。

引数

collectionId: 必須。 文字列。 コレクションの名前。 コレクションのメタデータを見ると、この値はメタデータのid値に対応します。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているプロパティに加えて、これらのプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
encodeURI trueに設定すると、collectionIdの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
ifMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致する場合にのみ、呼び出しは正常に完了します。 文字列 なし
ifNoneMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致しない場合にのみ、呼び出しは正常に完了します。 文字列 なし
sync このプロパティが存在し、値がtrueの場合、戻り値には、同期ライブラリがオフラインで使用するためにローカルにデータをキャッシュするために必要な情報が含まれます。 この値は、Oracle-Mobile-Sync-Agentリクエスト・ヘッダーから取得できます(存在する場合)。 Boolean false

レスポンス

戻り値には、次のヘッダーが含まれます:

ヘッダー 説明 タイプ
Cache-Control 結果をキャッシュする方法を説明します。 文字列
Etag 各アイテムにはETag値があります。 この値は、アイテムが更新されるたびに変更されます。 値には、開始および終了の二重引用符(たとえば、"2")が含まれます。 文字列

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIGET /mobile/platform/storage/collections/{collection}操作に示されているCollectionスキーマに従うJSONオブジェクトです。

次に、このメソッドを呼び出す例を示します。 syncプロパティがtrueに設定されているため、クライアント・アプリケーションはレスポンスをキャッシュできます。

req.oracleMobile.storage.getCollection('attachments', {sync: true}).then(
  function (result) {
    res.status(result.statusCode).send(result.result);
  },
  function (error) {
    res.status(error.statusCode).send(error.error);
  }
); 

レスポンス本文の例を次に示します:

{
    "id":"attachments",
    "description":"Attachments for technician notes.",
    "contentLength":6205619,
    "eTag":"\"1.0\"",
    "links":[
        {
            "rel":"canonical",
            "href":"/mobile/platform/storage/collections/attachments"},
        {
            "rel":"self",
            "href":"/mobile/platform/storage/collections/attachments"}
    ]}
storage.getCollections(options, httpOptions)

このメソッドは、モバイル・バックエンドを通じて使用可能な各コレクションに関するメタデータを返します。

引数

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているプロパティに加えて、これらのプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
limit 返されるアイテムの最大数。 リクエストされた制限が大きすぎる場合は、下限が代入されます。 整数 なし
offset 返される最初のアイテムの0から始まるインデックスです。 整数 0 (ゼロ)
sync このプロパティが存在し、値がtrueの場合、戻り値には、同期ライブラリがオフラインで使用するためにローカルにデータをキャッシュするために必要な情報が含まれます。 この値は、Oracle-Mobile-Sync-Agentリクエスト・ヘッダーから取得できます(存在する場合)。 Boolean false
totalResults このプロパティの値がtrueの場合、レスポンス本文には、コレクション内のアイテムの総数を表す値を持つtotalResultsプロパティが含まれます。 デフォルトでは、このプロパティは返されません。 Boolean false

レスポンス

戻り値には、次のヘッダーが含まれます:

ヘッダー 説明 タイプ
Cache-Control 結果をキャッシュする方法を説明します。 文字列
Oracle-Mobile-Sync-Resource-Type 同期ライブラリはこのヘッダーを使用します。 文字列

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIGET /mobile/platform/storage/collections操作に示されているCollection Arrayスキーマに従うJSON形式のitemsの配列です。

次に、このメソッドを呼び出す例を示します。 syncプロパティがtrueに設定されているため、クライアント・アプリケーションはレスポンスをキャッシュできます。

req.oracleMobile.storage.getCollections({sync: true}).then(
  function (result) {
    res.status(result.statusCode).send(result.result);
  },
  function (error) {
    res.status(error.statusCode).send(error.error);
  }
); 

レスポンス本文の例を次に示します:

{
    "items":[
        {
            "id":"logs",
            "description":"Application logs.",
            "contentLength":0,
            "eTag":"\"1.0\"",
            "links":[
                {
                    "rel":"canonical",
                    "href":"/mobile/platform/storage/collections/logs"},
                {
                    "rel":"self",
                    "href":"/mobile/platform/storage/collections/logs"}
            ]},
        {
            "id":"attachments",
            "description":"Attachments for technician notes.",
            "contentLength":6205619,
            "eTag":"\"1.0\"",
            "links":[
                {
                    "rel":"canonical",
                    "href":"/mobile/platform/storage/collections/attachments"},
                {
                    "rel":"self",
                    "href":"/mobile/platform/storage/collections/attachments"}
            ]}
    ],
    "hasMore":false,
    "limit":100,
    "offset":0,
    "count":2,
    "links":[
        {
            "rel":"canonical",
            "href":"/mobile/platform/storage/collections/"},
        {
            "rel":"self",
            "href":"/mobile/platform/storage/collections?offset=0&limit=100"}
    ]}
storage.remove(collectionId, objectId, options, httpOptions)

このメソッドは、オブジェクト識別子に基づいてオブジェクトをコレクションから削除します。

引数

collectionId: 必須。 文字列。 コレクションの名前。 コレクションのメタデータを見ると、この値はメタデータのid値に対応します。

objectId: 必須。 文字列。 削除するオブジェクトのID。

options: 任意。 JSONオブジェクト。 このオブジェクトは、共通オプション引数のプロパティにリストされているプロパティに加えて、これらのプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
encodeURI trueに設定すると、collectionIdobjectId、およびuserの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
ifMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致する場合にのみ、呼び出しは正常に完了します。 最後にリクエストした後にオブジェクトが変更されなかった場合にのみ、このプロパティを使用して操作が成功することを確認できます。 文字列 なし
ifModifiedSince HTTP-date形式の日付と時間。 たとえば、Mon, 30 Jun 2014 19:43:31 GMTです。 プロパティで指定された日付の後にオブジェクトが変更された場合にのみ、リクエストは正常に完了します。 日付 なし
ifNoneMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致しない場合にのみ、呼び出しは正常に完了します。 文字列 なし
ifUnmodifiedSince HTTP-date形式の日付と時間。 たとえば、Mon, 30 Jun 2014 19:43:31 GMTです。 このプロパティで指定された日付以降にオブジェクトが変更されなかった場合にのみ、リクエストは正常に完了します。 このプロパティを使用して、その時間後にオブジェクトを変更した人がいない場合にのみ操作が成功するようにすることができます。 日付 なし
user これはユーザーのID (ユーザー名ではない)です。 この問合せパラメータを使用すると、READ_ALL/READ_WRITE_ALL権限を持つユーザーは、別のユーザー隔離領域にアクセスできます。 READ/READ_WRITE権限を持つユーザーは、自分のスペースにのみアクセスできます。 文字列 共有コレクション内のオブジェクトを削除する場合、デフォルトはありません。

隔離されたコレクション内のオブジェクトを削除し、READ_ALL/READ_WRITE_ALLパーミッションを持っている場合、このプロパティを含めないと、サインインしたユーザーが引き継がれます。 隔離されたコレクションに対してREAD_ALL/READ_WRITE_ALLパーミッションがある場合、このプロパティを組み込んで、別のユーザーのスペースからオブジェクトを除去する必要があります。

この例では、attachmentsコレクションからオブジェクトを削除します:

service.delete('/mobile/custom/incidentreport/attachments/:id',
  function (req, res) {
    req.oracleMobile.storage.remove('attachments', req.params.id).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    );
  }); 
storage.store(collectionId, object, options, httpOptions)

このメソッドを使用すると、オブジェクトを格納し、そのオブジェクトに識別子を自動的に割り当てることができます。

引数

collectionId: 必須。 文字列。 コレクションの名前。 コレクションのメタデータを見ると、この値はメタデータのid値に対応します。

object: Required. テキスト、JSONオブジェクト、ファイル、またはバイナリ・オブジェクト。 格納するオブジェクト。

options: 任意。 JSONオブジェクト。 このオブジェクトは、「共通オプション引数のプロパティ」にリストされているものに加えて、次のプロパティを持つことができます。 contentTypeプロパティは、オブジェクトがリクエストされたときのメディア・タイプも指定するため、Storageにとって重要なロールを果たします。 contentを含まない場合、content-typeのデフォルトはapplication/octet-streamになります。

プロパティ 説明 タイプ デフォルト
contentLength バイト単位のオブジェクトのサイズ。 数値 オブジェクトが文字列またはバッファの場合、デフォルトはobject.lengthです。 それ以外の場合、デフォルトはメンバーの長さの合計です。
contentType 格納されているオブジェクトのメディア・タイプ。 このプロパティは、オブジェクトがリクエストされたときに返されるメディア・タイプも指定します。 文字列 inTypejsonの場合、Content-Typeヘッダーは自動的にapplication/jsonに設定されます。 それ以外の場合、デフォルトはapplication/octet-streamです。
encodeURI trueに設定すると、collectionIdmobileName、およびuserの値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
mobileName オブジェクトの表示名。 表示名を含めない場合、名前はこのメソッドが自動的に生成するオブジェクト識別子に設定されます。 文字列 なし
user これはユーザーのID (ユーザー名ではない)です。 この問合せパラメータを使用すると、READ_ALL/READ_WRITE_ALL権限を持つユーザーは、別のユーザー隔離領域にアクセスできます。 READ/READ_WRITE権限を持つユーザーは、自分のスペースにのみアクセスできます。 文字列 共有コレクションにオブジェクトを格納する場合、デフォルトはありません。

隔離されたコレクションにオブジェクトを格納していて、READ_ALL/READ_WRITE_ALLパーミッションを持っている場合、このプロパティを含めないと、サインインしたユーザーが引き継がれます。 隔離されたコレクションのREAD_ALL/READ_WRITE_ALLアクセス権を持っている場合、このプロパティを組み込んで、別のユーザーのスペースにオブジェクトを保管する必要があります。

レスポンス

戻り値には次のヘッダーが含まれます:

ヘッダー 説明 タイプ
Location 新しく作成されたオブジェクトに対応するURI。 文字列

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPOST /mobile/platform/storage/collections/{collection}/objects操作のレスポンス本文に示されているスキーマに従うJSONオブジェクトです。

この例では、リクエストにJSONオブジェクト、ファイル、プレーンテキスト、イメージなどを含めることができます。 入力がJSONオブジェクトの場合は、inTypejsonに設定し、オブジェクトのreq.bodyを渡す必要があります。 それ以外の場合は、inTypestreamに設定し、オブジェクトのreqを渡します。

service.post('/mobile/custom/incidentreport/attachments',
function (req, res) {
  if (req.is('json')) {
    // Must specify JSON because there is no stream to pipe from req
    // as Express has read it into json and put it in req.body.
    req.oracleMobile.storage.store('attachments', req.body,
      {
        mobileName: 'Technician Notes',
        inType: 'json',
        outType: 'stream'
      })
      .on('error', function (error) {
        res.status(error.statusCode).send(error.message)
      })
      .pipe(res);
  } else {
    // For streaming, send req instead of req.body
    req.oracleMobile.storage.store('attachments', req, {
      mobileName: 'Technician Notes',
      contentType: req.header('content-type'),
      inType: 'stream',
      outType: 'stream'
    })
      .on('error', function (error) {
        res.status(error.statusCode).send(error.message)
      })
      .pipe(res);
  }
});  

この例では、リクエスト本文にBase-64エンコードされたイメージが含まれています。 コードは、それを保存する前にバイナリ・イメージに変換します。 リクエスト本文は次のようになります:

{
  imageName: 'brokenWaterHose', 
  base74EncodedImage: '/9j/4AAQSkZJRg...AFFFFAH/2Q=='
}
// Base 64 
service.post('/mobile/custom/incidentreport/attachments',
  function (req, res) {
    // convert Base-64 encoded image to binary image
    image = new Buffer(req.body.base64EncodedImage);
    req.oracleMobile.storage.store('attachments', image,
      {
        contentType: 'image/jpeg',
        mobileName: req.body.imageName
      }
    ).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      }
    )
  })

レスポンス本文の例を次に示します:

{
    "eTag":"\"1\"",
    "id":"a95edb6f-539d-4bac-9ffa-78ff16b20516",
    "createdBy":"jdoe",
    "name":"Technician Notes",
    "createdOn":"2014-11-20T15:53:05Z",
    "modifiedOn":"2014-11-20T15:53:05Z",
    "modifiedBy":"jdoe",
    "links":[
        {
            "rel":"canonical",
            "href":"/mobile/platform/storage/collections/attachments/objects/a95edb6f-539d-4bac-9ffa-78ff16b20516"
        },
        {
            "rel":"self",
            "href":"/mobile/platform/storage/collections/attachments/objects/a95edb6f-539d-4bac-9ffa-78ff16b20516"
        }
    ],
    "contentType":"application/json",
    "contentLength":9377
}
storage.storeById(collectionId, objectId, object, options, httpOptions)

このメソッドは、指定したIDに基づいてオブジェクトを格納します。 自動的に生成されたIDの代わりに独自のIDを使用してオブジェクトを追加したり、既存のオブジェクトを更新したりすることができます。

引数

collectionId: 必須。 文字列。 コレクションの名前。 コレクションのメタデータを見ると、この値はメタデータのid値に対応します。

objectId: 必須。 文字列。 オブジェクトを追加する場合、これはオブジェクトを格納するIDです。 オブジェクトを更新する場合、これは置換するオブジェクトのIDです。

object: Required. テキスト、JSONオブジェクト、ファイル、またはバイナリ・オブジェクト。 これは格納するオブジェクトです。

options: 任意。 JSONオブジェクト。 このオブジェクトは、「共通オプション引数のプロパティ」にリストされているものに加えて、次のプロパティを持つことができます。

プロパティ 説明 タイプ デフォルト
contentLength バイト単位のオブジェクトのサイズ。 数値 オブジェクトが文字列またはバッファの場合、デフォルトはobject.lengthです。 それ以外の場合、デフォルトはメンバーの長さの合計です。
contentType 格納されているオブジェクトのメディア・タイプ。 このプロパティは、オブジェクトがリクエストされたときに返されるメディア・タイプも指定します。 文字列 inTypejsonの場合、Content-Typeヘッダーは自動的にapplication/jsonに設定されます。 それ以外の場合、デフォルトはapplication/octet-streamです。
encodeURI trueに設定すると、collectionIdobjectIdmobileName、およびuserの各値がURIエンコードされます。 このオプションは、マルチバイト値に便利です。 Boolean false
ifMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致する場合にのみ、呼び出しは正常に完了します。 最後にリクエストした後にオブジェクトが変更されなかった場合にのみ、このプロパティを使用して操作が成功することを確認できます。 文字列 なし
ifModifiedSince HTTP-date形式の日付と時間。 たとえば、Mon, 30 Jun 2014 19:43:31 GMTです。 プロパティで指定された日付の後にオブジェクトが変更された場合にのみ、リクエストは正常に完了します。 日付 なし
ifNoneMatch 対応するオブジェクトのETagがこのプロパティで指定された値のいずれかと一致しない場合にのみ、呼び出しは正常に完了します。 文字列 なし
ifUnmodifiedSince HTTP-date形式の日付と時間。 たとえば、Mon, 30 Jun 2014 19:43:31 GMTです。 このプロパティで指定された日付以降にオブジェクトが変更されなかった場合にのみ、リクエストは正常に完了します。 このプロパティを使用して、その時間後にオブジェクトを変更した人がいない場合にのみ操作が成功するようにすることができます。 日付 なし
mobileName オブジェクトの表示名。 表示名を含めない場合、名前はオブジェクト識別子に設定されます。 文字列 なし
user これはユーザーのID (ユーザー名ではない)です。 この問合せパラメータを使用すると、READ_ALL/READ_WRITE_ALL権限を持つユーザーは、別のユーザー隔離領域にアクセスできます。 READ/READ_WRITE権限を持つユーザーは、自分のスペースにのみアクセスできます。 文字列 共有コレクションにオブジェクトを格納する場合、デフォルトはありません。

隔離されたコレクションにオブジェクトを格納していて、READ_ALL/READ_WRITE_ALLパーミッションを持っている場合、このプロパティを含めないと、サインインしたユーザーが引き継がれます。 隔離されたコレクションのREAD_ALL/READ_WRITE_ALLアクセス権を持っている場合、このプロパティを組み込んで、別のユーザーのスペースにオブジェクトを保管する必要があります。

レスポンス

レスポンス本文は、Oracle Mobile Cloud ServiceのREST APIPUT /mobile/platform/storage/collections/{collection}/objects/{object}操作のレスポンス本文に示されているスキーマに従うJSONオブジェクトです。

この例では、リクエストにJSONオブジェクト、ファイル、プレーンテキスト、イメージなどを含めることができます。 入力がJSONオブジェクトの場合は、inTypejsonに設定し、オブジェクトのreq.bodyを渡す必要があります。 それ以外の場合は、inTypestreamに設定し、オブジェクトのreqを渡します。

service.put('/mobile/custom/incidentreport/attachments/:id',
function (req, res) {
  if (req.is('json')) {
    // Must specify JSON because there is no stream to pipe from req
    // as Express has read it into json and put it in req.body.
    req.oracleMobile.storage.storeById('attachments', req.params.id, req.body,
      {
        contentLength: req.body.length,
        mobileName: 'Technician Notes',
        inType: 'json',
        outType: 'stream'
      })
      .on('error', function (error) {
        res.status(error.statusCode).send(error.message)
      })
      .pipe(res);
  } else {
    // For streaming, send req instead of req.body
    req.oracleMobile.storage.storeById('attachments', req.params.id, req, {
      mobileName: 'Technician Notes',
      contentType: req.header('content-type'),
      inType: 'stream',
      outType: 'stream'
    })
      .on('error', function (error) {
        res.status(error.statusCode).send(error.message)
      })
      .pipe(res);
  }
});  

レスポンス本文の例を次に示します:

{
    "eTag":"\"2\"",
    "id":"incident412-notes",
    "createdBy":"jdoe",
    "name":"Technician Notes",
    "createdOn":"2014-11-20T15:57:04Z",
    "modifiedOn":"2014-11-20T15:58:09Z",
    "modifiedBy":"jdoe",
    "links":[
        {
            "rel":"canonical",
            "href":"/mobile/platform/storage/collections/attachments/incident412-notes"},
        {
            "rel":"self",
            "href":"/mobile/platform/storage/collections/attachments/incident412-notes"}
    ],
    "contentType":"application/json",
    "contentLength":9377
}

カスタム・コードからMobile Users APIへのアクセス

モバイル・ユーザーとモバイル・ユーザー拡張オペレーションAPIを使用すると、現在のモバイル、バーチャル、ソーシャル・ユーザーに関する情報を取得できます。 さらに、Mobile Users APIを使用すると、モバイル・ユーザーのカスタム・プロパティを更新できます。 カスタム・プロパティは、モバイル・クラウド管理者がユーザーのレルムに追加したプロパティです。

このAPIには、次のメソッドがあります:

ums.getUser(options, httpOptions)

このメソッドでは、現在のユーザーに関する情報を取得できます。

  • ユーザーがモバイル・ユーザーの場合、この操作ではユーザー名、名、姓、電子メール・アドレス、およびユーザーが所属するレルムに追加されたカスタム・プロパティが取得されます。

  • ユーザーが仮想ユーザーの場合、この操作はユーザー名を取得します。 仮想ユーザーについては、「仮想ユーザー用のSAMLトークンの構成」を参照してください。

  • ユーザーがソーシャル・ユーザー(ソーシャルIDを使用してサインインしている)の場合、この操作はユーザーID、アイデンティティ・プロバイダ、およびアクセス・トークンを取得します。 ソーシャル・ユーザーとソーシャル・アイデンティティについては、「MCSのFacebookログイン」を参照してください。

引数

options: 任意。 JSONオブジェクト。 モバイル・ユーザーの場合、このオブジェクトは共通オプション引数のプロパティにリストされているプロパティに加えて、次のプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
fields 取得するユーザー・プロパティを指定します。 たとえば、options.fieldsfirstName,lastNameに設定すると、これらの2つの値だけを取得できます。 現在のユーザーが仮想アイデンティティまたは社外アイデンティティを使用してサインインした場合、このプロパティは無視されます。 文字列 なし

レスポンス

現在のユーザーがソーシャル・ユーザーの場合、レスポンス本文には、この例に示すように、生成されたusernameプロパティとmobileExtended.identityProviderプロパティが含まれています。 ソーシャル・アイデンティティの詳細は、「MCSでのFacebookログイン」を参照してください。

    "username": "1 :623:165",
    "mobileExtended": {
        "identityProvider": {
            "facebook": {
                "accessToken":"CAAI...YZD"
            }
        }
    }

現在のユーザーが仮想ユーザーの場合、この例に示すように、レスポンス本文にはusernameが含まれます。

    "username": "a24x"

それ以外の場合は、レスポンス本文は、リクエストのoptions.fieldsプロパティの値に応じて、次のプロパティの1つ以上を含むJSONオブジェクトです。

  • id

  • email

  • firstName

  • lastName

  • username

  • ユーザーが属しているレルムに追加されたカスタム・プロパティ。

次に、このメソッドを呼び出してユーザーの姓と名を取得する例を示します。 この例では、ユーザーはモバイル・ユーザーです:

req.oracleMobile.ums.getUser({fields: 'firstName,lastName'}).then(
  function(result){
    res.send(result.statusCode, result.result);
  },
  function(error){
    res.send(error.statusCode, error.error);
  }
);

この例では、options.fieldsプロパティをfirstname,lastnameに設定したときに表示されるレスポンスを示します:

{
  "firstName": "Joe",
  "lastName": "Doe"
}

このメソッドを呼び出して、モバイル・ユーザーのすべてのフィールドを取得する例を次に示します:

req.oracleMobile.ums.getUser().then(
  function(result){
    res.send(result.statusCode, result.result);
  },
  function(error){
    res.send(error.statusCode, error.error);
  }
);

このリクエストのレスポンス本文の例を次に示します:

{
  "id":"295e450a-63f0-41fa-be43-cd2dbcb21598",
  "username":"joe",
  "email":"joe@example.com",
  "firstName":"Joe",
  "lastName":"Doe",
  "links":[
    {
      "rel":"canonical",
      "href":"/mobile/platform/users/joe"
    },
    {
      "rel": "self",
      "href": "/mobile/platform/users/joe"
    }    
  ]
}
ums.getUserExtended(options, httpOptions)

このメソッドを使用すると、ユーザーのロールを含む、承認されたユーザーに関する情報を取得できます。

  • ユーザーがモバイル・ユーザーの場合、この操作では、ユーザー名、名、姓、ロール、電子メール・アドレス、およびユーザーが所属するレルムに追加されたカスタム・プロパティが取得されます。

  • ユーザーが仮想ユーザーの場合、この操作はユーザー名とロールを取得します。 仮想ユーザーについては、「仮想ユーザー用のSAMLトークンの構成」を参照してください。

  • ユーザーがソーシャル・ユーザー(ソーシャルIDを使用してサインインしている)の場合、この操作はユーザーID、アイデンティティ・プロバイダ、およびアクセス・トークンを取得します。 ソーシャル・ユーザーとソーシャル・アイデンティティについては、「MCSのFacebookログイン」を参照してください。

引数

options: 任意。 JSONオブジェクト。 モバイル・ユーザーの場合、このオブジェクトは共通オプション引数のプロパティにリストされているプロパティに加えて、次のプロパティを持つことができます:

プロパティ 説明 タイプ デフォルト
fields 取得するユーザー・プロパティを指定します。 たとえば、options.fieldsfirstName,lastNameに設定すると、これらの2つの値だけを取得できます。 現在のユーザーが仮想アイデンティティまたは社外アイデンティティを使用してサインインした場合、このプロパティは無視されます。 文字列 なし

レスポンス

現在のユーザーがソーシャル・ユーザーの場合、レスポンス本文には、この例に示すように、生成されたusernameプロパティとmobileExtended.identityProviderプロパティが含まれています。

    "username": "1 :623:165",
    "mobileExtended": {
        "identityProvider": {
            "facebook": {
                "accessToken":"CAAI...YZD"
            }
        }
    }

現在のユーザーが仮想ユーザーの場合、この例に示すように、レスポンス本文にはusernameおよびrolesプロパティが含まれています。

    "username": "a24x",
    "roles": [
      "Customer", "Trial"
    ]

それ以外の場合は、レスポンス本文は、リクエストのoptions.fieldsプロパティの値に応じて、次のプロパティの1つ以上を含むJSONオブジェクトです。

  • id

  • email

  • firstName

  • lastName

  • username

  • roles (array)

  • ユーザーが属しているレルムに追加されたカスタム・プロパティ。

レスポンス本文には、リソースのAPIエンドポイントへのリンクも含まれています。

このメソッドを呼び出して、モバイル・ユーザーの名字を取得する例を次に示します:

req.oracleMobile.ums.getUserExtended({fields: 'firstName,lastName'}).then(
  function(result){
    res.send(result.statusCode, result.result);
  },
  function(error){
    res.send(error.statusCode, error.error);
  }
);

この例では、options.fieldsプロパティをfirstname,lastnameに設定したときに表示されるレスポンスを示します:

{
  "firstName": "Joe",
  "lastName": "Doe"
}

次に、このメソッドを呼び出して、モバイル・ユーザーのすべてのフィールドを取得する例を示します。

req.oracleMobile.ums.getUserExtended().then(
  function(result){
    res.send(result.statusCode, result.result);
  },
  function(error){
    res.send(error.statusCode, error.error);
  }
);

このリクエストのレスポンス本文の例を次に示します:

{
  "id":"295e450a-63f0-41fa-be43-cd2dbcb21598",
  "username":"joe",
  "email":"joe@example.com",
  "firstName":"Joe",
  "lastName":"Doe",
  "roles": [
    "Customer", "Trial"
  ],
  "links":[
    {
      "rel":"canonical",
      "href":"/mobile/platform/users/joe"
    },
    {
      "rel": "self",
      "href": "/mobile/platform/users/joe"
    }    
  ]
}
ums.updateUser(fields, options, httpOptions)

このメソッドでは、モバイル・バックエンドが関連付けられているレルムに追加されたカスタム・プロパティを更新できます。 このAPIは、usernameなどの組込みのプロパティの更新には使用できないことに注意してください。

引数

fields: Required. 更新するカスタム・フィールドの名前/値が含まれるJSONオブジェクト。 例: {birthdate: '07/21/71', language: 'en'} プリミティブ・データ型のみがサポートされています。

options: 任意。 「共通オプション引数のプロパティ」で説明されているJSONオブジェクト。

レスポンス

レスポンス本文は、名前/値ペアがユーザー・プロパティを表すJSONオブジェクトです。 リソースのAPIエンドポイントのリンクも含まれます。

このメソッドを呼び出して、カスタム・プロパティkeyを更新する例を次に示します。 この例では、リクエスト本文は{key: 'Ax47Y'}のようになります。
service.put(
  '/mobile/custom/incidentreport/key',
  function (req, res) {
    req.oracleMobile.ums.updateUser({key: req.body.key}).then(
      function (result) {
        res.send(result.statusCode, result.result);
      },
      function (error) {
        res.send(error.statusCode, error.error);
      }
    );
  });
レスポンス本文の例を次に示します:
{
  "id":"295e450a-63f0-41fa-be43-cd2dbcb21598",
  "username":"joe",
  "email":"joe@example.com",
  "firstName":"Joe",
  "lastName":"Doe",
  "key":"Ax47Y",
  "links":[
    {
      "rel":"canonical",
      "href":"/mobile/platform/users/joe"
    },
    {
      "rel": "self",
      "href": "/mobile/platform/users/joe"
    }    
  ]
}

カスタム・コードからカスタムAPIを呼び出す

カスタム・コードSDKは、他のカスタムAPIにリクエストを送信するための2つのネームスペースを提供します:

  • oracleMobile.custom.<apiName>: この名前空間のメソッドを使用するには、package.jsonにカスタムAPIへの依存関係を明示的に宣言する必要があります。

  • oracleMobile.custom: この名前空間内のメソッドを使用するには、package.jsonにカスタムAPIへの依存関係を明示的に宣言する必要はありません。

依存関係を追跡しやすくするなど、package.jsonの依存関係を宣言する理由はいくつかあります。また、APIを公開するときに依存APIが公開されるようにする必要があります。 package.jsonの依存関係を宣言する方法とその利点については、「カスタムおよびコネクタAPIへの呼び出しでのAPIバージョンの指定」を参照してください。

オプションのoptions引数は、「共通オプション引数のプロパティ」にリストされているものに加えて、このプロパティを持つことができます。

プロパティ 説明 タイプ デフォルト
versionToInvoke カスタムAPIのバージョン。

oracleMobile.custom名前空間を使用する場合、APIバージョンがpackage.jsonで宣言されていない場合は、このオプションを含める必要があります。

oracleMobile.custom.<apiName> 名前空間を使用する場合は、package.jsonでAPIバージョンを宣言し、オプションでこのプロパティを使用してそのバージョンをオーバーライドする必要があります。

文字列 package.jsonファイルで宣言されているバージョン。

両方のネームスペースは、次の表に示すように、各HTTP操作のメソッドを提供します:

HTTP操作 oracleMobile.customメソッド oracleMobile.custom.<apiName>メソッド
GET get(apiName, resourceName, options, httpOptions) get(resourceName, options, httpOptions)
PUT put(apiName, resourceName, object, options, httpOptions) put(resourceName, object, options, httpOptions)
POST post(apiName, resourceName, object, options, httpOptions) post(resourceName, object, options, httpOptions)
DELETE del(apiName, resourceName, options, httpOptions) del(resourceName, options, httpOptions)
HEAD head(apiName, resourceName, options, httpOptions) head(resourceName, options, httpOptions)
OPTIONS options(apiName, resourceName, options, httpOptions) options(resourceName, options, httpOptions)
PATCH patch(apiName, resourceName, object, options, httpOptions) patch(resourceName, object, options, httpOptions)

次に、両方の名前空間を使用してカスタム・コードから別のカスタムAPIを呼び出す方法の例を示します。 これらの例では、motdカスタムAPIを呼び出し、そのyears/{year}/months/{month}/daysリソースにPOSTリクエストを送信します。

  /**
   *  oracle.Mobile.custom.<apiName> namespace example:
   *
   *  <namespace>.post(<resource>, <body>, <options>)
   *
   *  Note: Because it uses the 
   *  oracleMobile.custom.<apiName> namespace,
   *  the dependency on the motd API must
   *  be specified in package.json.
   *  options.versionToInvoke isn't required. You can use
   *  it to override the version that is declared in 
   *  package.json.
   */      
  req.oracleMobile.custom.motd.post(
    'years/2018/months/1/days', 
    req.body, 
    {inType: 'json'}).then(
    function (result) {
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      res.status(error.statusCode).send(error.error);
    }
  );       
  /**
   *  oracle.Mobile.custom namespace example:
   *
   *  post(<namespace>, <resource>, <body>, <options>)
   *
   *  You must include the versionToInvoke option if
   *  the API isn't declared in package.json.
   */      
  req.oracleMobile.custom.post(
    'motd',
    'years/2018/months/1/days', 
    req.body, 
    {versionToInvoke: '1.0', inType: 'json'}).then(
    function (result) {
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      res.status(error.statusCode).send(error.error);
    }
  ); 

カスタム・コードからConnector APIを呼び出す

コネクタを使用するには、カスタムAPIを作成し、SDKのコネクタ・メソッドを呼び出すコードを実装する必要があります。 ここでカスタム・コードからコネクタを呼び出す方法について説明します。

ヒント:

有効な記述子を使用して作成したREST APIの場合は、「コネクタからカスタムAPIを生成する方法」で説明されているように、カスタムAPIとその実装を自動的に作成できます。 自動生成機能を使用する場合は、生成されたコードに含まれているカスタマイザ・メソッドを使用している場合を除き、ここで説明するSDKのコネクタ・メソッドの使い方を一般的に知る必要はありません。 たとえば、options.externalAuthorizationを渡すためにカスタマイザを使用する必要があるかもしれません。 場合によっては、マルチパート・フォーム・データまたはhttpオプション・オブジェクトを送信する必要がある場合など、callConnectorメソッドの呼び出しを独自のコードに置き換える必要があります。

カスタム・コードSDKは、コネクタにリクエストを送信するための2つのネームスペースを提供します:

  • oracleMobile.connectors.<connector>: この名前空間でメソッドを使用するには、package.jsonにコネクタへの依存関係を明示的に宣言する必要があります。 自動的に生成された実装はこの名前空間を使用します。

  • oracleMobile.connectors: この名前空間でメソッドを使用するには、package.jsonにコネクタへの依存関係を明示的に宣言する必要はありません。

依存関係を追跡しやすくするなど、package.jsonの依存関係を宣言する理由はいくつかあります。また、APIを公開するときに依存APIが公開されるようにする必要があります。 package.jsonの依存関係を宣言する方法とその利点については、「カスタムおよびコネクタAPIへの呼び出しでのAPIバージョンの指定」を参照してください。

オプションのoptions引数には、「共通オプション引数のプロパティ」にリストされているプロパティに加えて、これらのプロパティを含めることができます。

プロパティ 説明 タイプ デフォルト
externalAuthorization コネクタのセキュリティ・ポリシーを構成していない場合は、外部サービスのAuthorization値をoptions.externalAuthorizationプロパティに入れます。 このプロパティが存在する場合、コネクタは、リクエストを外部サービスに送信する前に、options.externalAuthorizationプロパティの値を含む発信Authorizationヘッダーを設定します。 文字列 なし
versionToInvoke コネクタのバージョン。

oracleMobile.connectors名前空間を使用する場合、APIバージョンがpackage.jsonで宣言されていない場合は、このオプションを含める必要があります。

oracleMobile.connectors.<connector> 名前空間を使用する場合は、package.jsonでAPIバージョンを宣言し、オプションでこのプロパティを使用してそのバージョンをオーバーライドする必要があります。

文字列 package.jsonファイルで宣言されているバージョン。 oracleMobile.connectors.<connector> 名前空間を使用する場合、APIバージョンはpackage.jsonで宣言する必要があります。

両方のネームスペースは、次の表に示すように、各HTTP操作のメソッドを提供します:

HTTPメソッド oracleMobile.connectorsシグネチャ oracleMobile.connectors。<connector>シグネチャ
GET get(connector, resourceName, options, httpOptions) get(resourceName, options, httpOptions)
PUT put(connector, resourceName, object, options, httpOptions) put(resourceName, object, options, httpOptions)
POST post(connector, resourceName, object, options, httpOptions) post(resourceName, object, options, httpOptions)
DELETE del(connector, resourceName, options, httpOptions) del(resourceName, options, httpOptions)
HEAD head(connector, resourceName, options, httpOptions) head(resourceName, options, httpOptions)
OPTIONS options(connector, resourceName, options, httpOptions) options(resourceName, options, httpOptions)
PATCH patch(connector, resourceName, object, options, httpOptions) patch(resourceName, object, options, httpOptions)

注意:

Network_HttpPatch環境ポリシーを使用して、PATCHリクエストの動作を制御します。
  • HEADERは、X-HTTP-Method-OverrideヘッダーがPATCHに設定されたPOSTリクエストを送信します。 これにより、ターゲット・サーバーがPATCHメソッドをサポートしていない場合にPATCHリクエストを送信できます。

  • LEGACYは、X-HTTP-Method-OverrideヘッダーがPATCHに設定されたPATCHリクエストを送信します。 これは、18.2.3より前にプロビジョニングされた環境の動作と一致しています。

  • METHODは、X-HTTP-Method-OverrideヘッダーをPATCHに設定せずにPATCHリクエストを送信します。

18.2.3より前にプロビジョニングされた環境では、デフォルトはLEGACYです。 18.2.3以降でプロビジョニングされた環境の場合、デフォルトはMETHODです。 MyRESTConnectorのポリシーを変更するためのポリシー設定の使用例を次に示します:

*.connector/MyRESTConnector(1.0).Network_HttpPatch=HEADER

環境ポリシーの表示と変更については、「環境ポリシーの変更」を参照してください。

次に、oracleMobile.connectors名前空間を使用して/mobile/connector/globalweatherコネクタを呼び出す例を示します:

req.oracleMobile.connectors.post('globalweather', 'GetWeather', body,
{inType: 'json', versionToInvoke: '1.0'}).then(
  function (result) {
    console.info("result is: " + result.statusCode);
    res.status(result.statusCode).send(result.result);
  },
  function (error) {
    console.info("error is: " + error.statusCode);        
    res.status(error.statusCode).send(error.error);
  }
);

次に、oracleMobile.connectors.<connector>名前空間を使用して/mobile/connector/globalweatherコネクタを呼び出す例を示します。

req.oracleMobile.connectors.globalweather.post('GetWeather', body, {inType: 'json'}).then(
  function (result) {
    res.status(result.statusCode).send(result.result);
  },
  function (error) {      
    res.status(error.statusCode).send(error.error);
  }
);

REST Webサービスへのコネクタの呼び出し

REST APIコネクタを呼び出すには、コネクタ名とリソース名が必要です。 エンドポイントからベースURIを削除してリソース名を形成します。 たとえば、gitコネクタがhttps://example.comにマップされているとします。 https://example.com/{owner}/{repo}/contents/{path}を呼び出すには、resourceName{owner}/{repo}/contents/{path}に設定します。

また、options.externalAuthorizationまたはhttpOptions.headers['oracle-mobile-external-authorization']のいずれかで認可を渡す必要があります。

PUTリクエストをRESTコネクタに送信する例を次に示します:

service.put('/mobile/custom/incidentreport/connectors/git/:owner/:repo/contents/:path',
  function (req, res) {
    req.oracleMobile.connectors.idmsamples.put(
      'repos/' + req.params.owner + '/' + req.params.repo + '/contents/' + req.params.path, 
      req.body, 
      {externalAuthorization: req.header('external-authorization'), inType: 'json'}, 
      null).then(
        function (result) {
          // include the target service's response headers
          res.set(result.headers);
          res.status(result.statusCode).send(result.result);
        },
        function (error) {
          res.status(error.statusCode).send(error.error);
        }
    );
});

httpOptionsオブジェクトを使用して、ヘッダーと問合せパラメータをコネクタに渡します。

注意:

REST webサービスへのコネクタには、デフォルトの問合せパラメータを設定するルールを設定できます。 これらの同じパラメータに値を指定すると、値が優先され、コネクタ・ルールのデフォルト・パラメータがオーバーライドされます。

httpOptionsオブジェクトの問合せパラメータとヘッダーを渡す例を次に示します:

service.get('/mobile/custom/incidentreport/connectors/git/:owner/:repo/contents/:path',
  function (req, res) {
    req.oracleMobile.connectors.idmsamples.get(
      'repos/' + req.params.owner + '/' + req.params.repo + '/contents/' + req.params.path,
      {externalAuthorization: req.header('external-authorization')}, 
      {qs: {"branch": req.query.branch}, headers: {"accept": req.header('accept')}}
       ).then(
        function (result) {
          res.status(result.statusCode).send(result.result);
        },
        function (error) {
          res.status(error.statusCode).send(error.error);
        }
      );    
});

ヒント:

httpOptions.qsを使用して問合せ文字列を渡すときは、qs値にencodeURIComponent(<string>) を使用して、コードがマルチバイト文字を処理するようにすることができます。

RESTサービスへのコネクタの作成方法については、「RESTコネクタAPI」を参照してください。

SOAPサービスへのコネクタの呼び出し

SOAPコネクタに送信するメッセージの本文は、オプションのHeader、必須のBody、およびオプションのFaultを使用して、SOAPエンベロープのXMLまたはJSON形式のいずれかでなければなりません。

JSONリクエストは自動的にXMLに変換され、XMLレスポンスはJSONに変換されます。 つまり、XMLを扱うことなくSOAPサービスとやりとりすることができます。 翻訳が行われるときに注意すべき条件については、「XMLはどのようにJSONに変換されますか?」を参照してください。

XMLでメッセージを提供することを選択した場合、次のことを忘れないでください:

  • レスポンス本文がXML形式であることをリクエストするには、options.acceptapplication/xmlに設定します。

  • リクエスト本文がXML形式の場合は、options.contentTypeapplication/xml; charset=utf-8に設定します。

  • リクエスト本文のXMLは、SOAPエンベロープにラップする必要があります。このエンベロープには、この例に示すように、必要なSOAPヘッダーが含まれている必要があります。 SOAPヘッダーをメッセージで送信する必要があるコネクタにセキュリティ・ポリシーを構成した場合、そのヘッダーは自動的に追加されるため、メッセージに含める必要はありません。

    <?xml version="1.0" ?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemad.xmlsoap.org/soap/envelope">
    
      <SOAP-ENV:Header>
        <!-- Add any SOAP headers here -->
      </SOAP-ENV>
    
      <SOAP-ENV:Body>
        <!-- Add the Body element here -->
      </SOAP-ENV:Body>
    
    </SOAP-ENV:Envelope>

コネクタの操作に関するサンプル・メッセージを表示するには、コネクタのテスト・ページで操作を選択し、「例」をクリックします。

SOAPコネクタでは、options.contentTypeプロパティで文字セットが指定されていない場合は、UTF-8が使用されます。

次に、SOAPサービスへのコネクタの呼び出し例を示します。 この例では、リクエスト本文はJSON形式です:

service.get('/mobile/custom/incidentreport/connectors/numberConvert/:number/words',
function (req, res) {
  var body = {
    Header: null,
    Body: {
       "NumberToWords": {
          "ubiNum": req.params.number
      }
    }
  };
  req.oracleMobile.connectors.post('numberConvert', 'words', body,
  {inType: 'json', versionToInvoke: '1.0'}).then(
    function (result) {
      res.status(result.statusCode).send(result.result);
    },
    function (error) {      
      res.status(error.statusCode).send(error.error);
    }
  );
});

SOAPサービスへのコネクタを作成する方法については、「SOAPコネクタAPI」を参照してください。

フォーム・データを必要とするコネクタの呼び出し

コネクタの操作にコンテンツ・タイプmultipart/form-dataが必要な場合は、Multerを使用してフォーム・データをコネクタに渡します。 Multerは、マルチパート・フォーム・データを扱うNode.jsのライブラリです。

multipart/form-data型のリクエスト本文を持つコネクタを呼び出すには:

  1. 次の例に示すように、multerpackage.jsonの依存関係として追加し、npm installを実行します。

    {
      "name": "sendformdata",
      "version": "1.0.0",
      "description": "Sends form data to a connector API.",
      "main": "sendformdata.js",
      "dependencies": {
        "multer": "latest"
      },
      ...
    }
  2. カスタム・コードで、次のステートメントを追加します:

    var multer = require('multer');
    var storage = multer.memoryStorage();
    var upload = multer({storage: storage});
    

    multipart/form-data型の場合、Multerは次のオブジェクトを着信リクエスト本文に追加します:

    • body: フォーム内にあるテキスト・フィールドを含みます。

    • files: フォームを使用してアップロードされたファイルを含みます。

  3. 操作のメソッドでは、2番目の引数としてupload.arrayを渡して、フォームのファイル・パラメータの名前とアップロードされたファイルの最大数を指定します。 次に例を示します。

    service.post('/mobile/custom/SendFormData/upload', upload.array("avatar", 12), function (req, res)
  4. bodyオブジェクトとfilesオブジェクトからコンテンツを抽出し、httpOptions.formDataオブジェクトを介してコネクタに渡します。 ファイル・オブジェクトをストリームのように見えるようにする必要があります。

ここに例があります。 この例では、POST /mobile/custom/SendFormData/upload操作には次のフォーム・パラメータが必要です:

  • username、タイプtextのものです。

  • avatar、タイプfileのものです。

var multer = require('multer');
var storage = multer.memoryStorage();
var upload = multer({storage: storage});

module.exports = function (service) {

   service.post('/mobile/custom/SendFormData/upload', upload.array("avatar", 12), function (req, res) {

    // Because the uploaded file is a buffer in memory, you must modify it
    // to look like a stream before you send it to the connector.
    var uploadedFile = {
      value: req.files[0].buffer,
      options: {
        filename: req.files[0].originalname,
        contentType: req.files[0].mimetype
      }
    };
    
    var formData = {
      username: req.body.username,
      avatar: uploadedFile
    };

    // FormData is the name of the connector.
    // The formData object is passed in the httpOptions argument.
    // The options.contentType is set to multipart/form-data automatically.
    req.oracleMobile.connectors.FormData.post("upload", null, null, {
      formData: formData
    }).then(
      function (result) {
        res.status(result.statusCode).send(result.result);
      },
      function (error) {
        res.status(error.statusCode).send(error.error);
      });
  });
};

Multerについては、https://www.npmjs.com/package/multerを参照してください。

ターゲット・サービスにヘッダーを渡す

次のヘッダーを除いて、ヘッダーとその値を渡すには、httpOptions.headersを使用する必要があります:

  • 認可:コネクタにコネクタ認可ヘッダー・ルールがない場合、またはルールのデフォルト値を使用しない場合、ここに示すように、options.externalAuthorizationプロパティまたはhttpOptions.headers['oracle-mobile-external-authorization']プロパティのいずれかに指定します。 「セキュリティとRESTコネクタAPI」を参照してください。

  • Connection: このヘッダーは設定しないでください。

  • Content-Length: このヘッダーは設定しないでください。

  • Host: このヘッダーは設定しないでください。

  • User-Agent: このヘッダーは設定しないでください。

注意:

元のリクエストのAccept値は、対象のサービスに渡されません。 ターゲット・サービスに値を渡すには、httpOptions.headers.acceptプロパティまたはoptions.acceptプロパティのいずれかを使用します。

リクエストに渡すヘッダーは、コネクタ・ルールによって設定された関連するすべてのデフォルト値をオーバーライドします。

ターゲット・サービスにヘッダーを渡す例を次に示します:

  var httpOptions={'headers':{}};
  // You must pass the Accept header if you don't want to use the target server's default.
  if (req.header('accept')) {
    // You can pass the accept value using options.accept or httpOptions.header, as shown here:
    httpOptions.headers.accept = req.header('accept');
  };
  // If the connector doesn't have an Authorization rule, 
  // or if you don't want to use the rule's default,
  // pass the authorization information using options.externalAuthorization or
  // httpOptions.headers.oracle-mobile-external-authorization.
  // Note the ['']syntax to prevent the hyphen from being interpreted as a minus.
  if (req.header('external-authorization')) {
      httpOptions.headers['oracle-mobile-external-authorization'] = 
        req.header('external-authorization');
  };
  // Pass any custom headers    
  if (req.header('if-none-match')) {
     httpOptions.headers['if-none-match'] = req.header('if-none-match');
  }; 
  req.oracleMobile.connectors.git.get('repos/fixItFast/incidentreport/contents/README.md', 
    null,
    httpOptions).then(
    function (result) {
      // include the target service's headers
      res.set(result.headers);
      res.status(result.statusCode).send(result.result);
    },
    function (error) {
      res.status(error.statusCode).send(error.error);
    }
  );

コネクタのSSL設定を上書きします

サービスに無効なSSL証明書があるか、リクエストがリダイレクトされるなど、外部サービスに問題が発生する可能性がありますが、リダイレクトでCookieが保持されません。

これらの問題を解決するには、options引数を使用して、プロキシを経由する発信HTTPリクエストをカスタマイズします。 プロキシはreq.oracleMobile.proxy.httpProxyから取得できます。 SSL検証の問題を無視するためにstrictSSL設定を上書きする方法の例を次に示します。

var res = {};
var options = { 
  uri: req.body.externalURI, 
  strictSSL: false, 
  proxy: 'http://' + req.oracleMobile.proxy.httpProxy
} 
req(options).pipe(res);

リクエスト・オプションの詳細については、https://github.com/request/request#requestoptions-callbackを参照してください。

カスタムおよびコネクタAPIへの呼び出しでのAPIバージョンの指定

コネクタAPIまたはその他のカスタムAPIを呼び出すときは、常にAPIバージョンを指定する必要があります。 APIバージョンは、次のいずれかの方法で指定できます:

  • ここに示すように、バージョンの依存関係を実装のpackage.jsonファイルに明示的に記述します。 oracleMobile.connectors.<connector>またはoracleMobile.custom.<apiName>名前空間でメソッドを使用する場合は、これを行う必要があります。

    {
      "name" : "incidentreports",
      "version" : "1.0.0",
      "description" : "FixItFast Incident Reports API",
      "main" : "incidentreports.js",
      "oracleMobile" : {
        "dependencies" : {
          "apis" : {"/mobile/custom/motd" : "1.0"},
          "connectors" : {"/mobile/connector/geocoder": "1.0"}
        }
      }
    }

    この例では、oracleMobile.custom.motd名前空間内の任意のメソッドの呼び出しは、デフォルトでバージョン1.0を使用します。

    詳細は、「package.json内容」を参照してください。

  • リクエストにoptions.versionToInvokeプロパティを組み込み、使用するバージョン(文字列として表されます)に設定します。 この方法でバージョン番号を指定すると、package.jsonファイルで指定したバージョンが上書きされます。

    req.oracleMobile.custom.post(
        'motd',
        'years/2018/months/1/days', 
        req.body, 
        {versionToInvoke: '1.0', inType: 'json'}).then(
        function (result) {
          res.status(result.statusCode).send(result.result);
        },
        function (error) {
          res.status(error.statusCode).send(error.error);
        }
      );
    

    注意:

    ジェネリックなoracleMobile.rest名前空間のメソッドを使用している場合は、options.versionToInvokeプロパティの代わりにOracle-Mobile-API-Versionヘッダーにバージョンを入れてください。

package.jsonファイルを使用して依存関係を宣言すると、依存関係を宣言するためにoptions.versionToInvokeプロパティを使用する場合よりも、それらの依存関係を追跡する方が簡単です。 この目的のためにpackage.jsonを使用すると、APIデザイナは実装のリストの下の表に依存関係を表示します。 APIの公開を準備すると、未発行の依存APIを公開するように求められます。

ただし、options.versionToInvokeプロパティを使用して依存APIのバージョンを宣言すると、APIデザイナはその依存関係を認識せず、呼び出し元のAPIを公開するときに情報を要求しません。 この場合、依存するAPIを自分で公開することを忘れないでください。

汎用RESTメソッドを使用したAPIへのアクセス

以前のバージョンのカスタム・コードSDKでは、カスタム、プラットフォーム、およびコネクタAPIにアクセスするためにoracleMobile.restメソッドが使用されていました。 下位互換性を確保するために、これらのメソッドは引き続き使用可能です。

レガシー・メソッドには2つのオプションがあります: リクエストの詳細を渡すために使用するoptionsListと、メソッドによって実行されるオプションの機能であるhandlerがあります。 handler引数を指定しないと、このメソッドは約束を返します。 約束は、非同期リクエストの結果を表します。 それが発行された時点で、リクエストは完了していてもいなくてもよい。 通常、then関数を使用して約束します。

handler関数が他のカスタムAPI、プラットフォームAPI、またはコネクタAPIを呼び出す場合は、Request.jsの規則に従わなければなりません(https://github.com/request/requestで説明)。

このAPIには、次の表に示すように、HTTP操作ごとにレガシー・メソッドと非同期メソッドがあります。 レガシー・メソッドと非同期メソッドの違いは、非同期メソッドにはhandler引数がないことです。 彼らはいつも約束を返す。
HTTP操作 メソッドoracleMobile.rest
GET get(optionsList, handler)

getAsync(optionsList)

PUT put(optionsList, handler)

putAsync(optionsList)

POST post(optionsList, handler)

postAsync(optionsList)

DELETE del(optionsList, handler)

delAsync(optionsList)

HEAD head(optionsList, handler)

headAsync(optionsList)

OPTIONS options(optionsList, handler)

optionsAsync(optionsList)

PATCH patch(optionsList, handler)

patchAsync(optionsList)

次に、oracleMobile.restメソッドを使用してデータベース・サービスAPIにアクセスする例を示します。 optionsListを使用してURIと問合せ文字列を渡し、リクエスト本文をJSONに変換する方法に注目してください。

// The request body looks like this
// {title:'Water heater is leaking', technician:'jwhite',customer:'Lynn Smith'}
service.post('/mobile/custom/incidentreport/incidents',
function (req, res) {

  var optionsList = {
    uri: '/mobile/platform/database/objects/FIF_Incidents',
    qs: req.query,
    json: req.body,
    headers: {
      'Oracle-Mobile-Extra-Fields': 'createdBy,createdOn'
    }
  };

  req.oracleMobile.rest.post(optionsList, function (error, response, body) {
    var message = error ? error.message : body;
    res.status(response.statusCode).send(message);
  });
});

optionsList引数

optionsList引数を使用して、URI、本文、ヘッダーなどのoracleMobile.rest呼び出しのリクエストの詳細を渡します。 構成できるオプションのいくつかの例を以下に示します:

body

このオプションには、patchpost、またはputリクエストの本文が含まれます。 OptionsList.jsontrueに設定されていない限り、値はBufferまたはStringでなければなりません。 OptionsList.jsontrueの場合、本文はJSON直列化可能オブジェクトでなければなりません。 このリストのjsonオプションも参照してください。

headers

このオプションには、HTTPヘッダーのリストが含まれます。 次に例を示します。

optionsList.headers=
{Content-Type : 'application/json;charset=UTF-8'};

注意:

jsonオプションを使用する場合は、Content-Typeヘッダーを指定する必要はありません。 それ以外の場合は、リクエストに本文がある場合は、このヘッダーを組み込み、charsetを指定します。
json
このオプションは、次の2つの方法で使用できます:
  • JavaScriptオブジェクトを保持します。 この場合、リクエストが送信されると、オブジェクトはJSONに変換されてHTTP本文に入れられ、Content-Type: application/jsonヘッダーが自動的に追加されます。

  • 値をtrueに設定することによって、optionsList.bodyの値がJavaScriptオブジェクトであることを示します。 この場合、リクエストが送信されると、optionsList.bodyの値がJSONに変換されてHTTP本文に入れられ、Content-Type: application/json;charset=UTF-8ヘッダーが自動的に追加されます。

timeout

このオプションは、リクエストを終了する前にリクエストが応答するまで待機するミリ秒数を指定します。 このオプションを指定しないと、タイムアウト値はデフォルトでNetwork_HttpRequestTimeout環境ポリシーで指定されたタイムアウトになります。

この値は、実装がデプロイされる環境のNetwork_HttpRequestTimeout環境ポリシーよりも大きくないようにしてください。 このポリシー設定の価値については、クラウド管理者に問い合わせてください。

ターゲットURIがコネクタの場合、その値はコネクタのNetwork_HttpConnectTimeoutおよびNetwork_HttpReadTimeoutポリシーよりも大きくなければなりません。 これらの値は、コネクタの構成ページに表示されます。

uri

この必須オプションには、呼び出すAPIを一意に識別するURLフラグメントが含まれています。 次に例を示します。

/mobile/platform/storage/collections/coll1/objects

ここにリストされているオプションに加えて、Request.js APIで指定されたオプションを指定できます。 https://github.com/mikeal/requestのAPIドキュメントに移動し、request(options, callback)というセクションまでスクロールします。

プラットフォーム、カスタム、およびコネクタAPIについて学ぶ

APIカタログを使用して、プラットフォームAPI、カスタムAPI、およびコネクタAPIについて知ることができます。 APIカタログにアクセスするには、アイコンをクリックしてサイド・メニューを開きますをクリックしてサイド・メニューを開き、APIを選択します。

  • プラットフォームAPIのエンドポイントを表示するには、APIカタログの一番下までスクロールし、APIを選択します。

  • カスタムAPIまたはコネクタAPIのエンドポイントを表示するには、カスタムAPIを開き、「実装」をクリックし、「カスタム・コードAPIカタログ」をクリックします。 「表示」リストから、「コネクタAPI」を選択するか、APIのタイプに応じて「モバイルAPI」を選択し、そのエンドポイントを表示するAPIを選択します。

Oracle Mobile Cloud ServiceのREST APIでは、APIカタログに加えて、プラットフォームAPIの情報も提供されています。 たとえば、cURLの例と、リクエストとレスポンスの本文とヘッダーの詳細を提供します。