ThingWorx Flow > ThingWorx Flow SDK > 付録 B: ThingWorx Flow コネクタ SDK チュートリアル
付録 B: ThingWorx Flow コネクタ SDK チュートリアル
前提条件
このチュートリアルでは以下を必要とします。
LTS バージョンの Node.js 8.9.0 + インストーラ
Node js プロジェクトを処理可能な統合開発環境 (IDE)
このチュートリアルでは統合開発環境として WebStorm を使用しています。
Node js コードについての中程度の知識
サンプルフォルダ
概要
このチュートリアルでは、一般的なコネクタを構築するために必要な手順について説明します。多くの開発者が Gmail を使い慣れていると思われるので、Gmail 用のコネクタを構築します。このコネクタを構築することにより、コネクタの構築に関連するツール、成果物、プロセスについての理解を深め、ご自身のアプリケーション用にコネクタを構築できるようになります。新規コネクタを構築するために ThingWorx Flow を展開する必要はありません。コネクタをローカルで構築およびテストした後、テスト用のオンプレミスのテストインストールにこれを展開できます。
このチュートリアルでは以下について説明します。
1. コネクタプロジェクトの作成。
2. OAuth2 コンフィギュレーション
3. Gmail アカウントで関連するフィルタをサーチする検索の作成。
4. 選択したフィルタと一致する電子メールメッセージの ID と件名を取得する操作の作成。
5. 新規メールを受信したときに新しいフローを開始するトリガーの作成。
6. アイコンの追加
7. ThingWorx Flow のオンプレミスインスタンスへのコネクタの展開。
コネクタプロジェクトの作成
コネクタは、OAuth コンフィギュレーション、操作、検索、トリガーなどの各種成果物から成る特別な npm パッケージです。プロジェクトはパターンに従って npm パッケージを構築する必要があります。プロジェクトには package.json、ライブラリフォルダ、テストフォルダ、および各成果物とそのバージョンのフォルダがあります。
terminal/cmd ウィンドウを開き、新規コネクタプロジェクトを作成するフォルダに移動します。このチュートリアルでは、ディレクトリ c:\test にコネクタを作成します。
1. ディレクトリをテストディレクトリに変更します: cd c:\test
2. 次のコマンドを実行してプロジェクトを作成します: flow init <projectname>
以下が表示されます。
cd c:\test
[2018-10-21T15:35:11.519] [INFO] default - Project gmail created successfully in .
3. 統合開発環境でプロジェクトディレクトリを開き、デフォルトで作成された成果物をレビューします。
各プロジェクトには index.js ファイルと package.json ファイルが含まれています。index.js ファイルは、ThingWorx Flow サーバーにコネクタをロードするために必要であるため、このファイルを変更しないでください。
* 
package.json ファイルは ptc-flow-sdk を参照します。この依存がない場合、コネクタをテスト、展開、実行することはできません。コネクタの開発をより簡単で一貫したものにするいくつかの API も提供されます。
1. 付録 Aの手順に従います。
2. 以下のコマンドを使用して async パッケージをインストールします。
npm install async
3. 以下のコマンドを使用して、request モジュールをインストールします。リクエストモジュールには HTTP リクエストを行うための API が含まれています。
npm install request
npm install request-promise
4. 多数の便利な機能を提供する lodash モジュールをインストールします。
npm install lodash
npm install ptc-flow-sdk@<ツールのバージョン> -g
お使いのバージョンの ThingWorx Flow に対応する <ツールのバージョン> については、 ここで確認してください。
* 
チュートリアル内のすべてのコマンドは、コネクタプロジェクトのディレクトリ c:\test\gmail から実行します。これにより、-d/--projectDir オプションを使用して、コネクタのディレクトリへの完全なパスを指定する必要がなくなります。
OAuth2 コンフィギュレーションの作成
* 
開始する前に、「OAuth とトリガーをテストするためのコンフィギュレーション」セクションの手順に従います。
Gmail では認証に OAuth 2.0 が使用されます。このため、サンプルコネクタは認証メカニズムとして OAuth 2.0 を使用します。すべての OAuth2 プロバイダは、アプリケーションに対して、クライアント ID とクライアントシークレットを作成するよう要求します。この後、アプリケーションはユーザーが各自の資格証明を使用して OAuth プロバイダにログインするようリクエストできます。ユーザーは自分の代わりにデータにアクセスするためのアクセス許可をアプリケーションに付与できます。アクセス許可はスコープによって定義します。ユーザーはアプリケーションに対して自分のデータへのアクセス権を選択的に付与できます。Gmail およびその他の Google アプリケーションでのこの実装方法の詳細については、以下のリンクにアクセスしてください。
リダイレクト URL を入力します。リダイレクト URL:
https://<ホスト名>:<ポート>//Thingworx/Oauths/oauth/return は以下のようになります。
https://flow.local.rnd.ptc.com/Thingworx/Oauths/oauth/return
一部のシステムでは複数のリダイレクトを指定できます。
* 
使用するホストがユーザーのホームディレクトリ内の .flow\flow.json ファイルに追加されていることを確認します。これが実際のホスト名ではなくローカルホストへのエイリアスである場合、お使いのオペレーティングシステムのホストファイルにこれを追加します。
たとえば、次のようになります。
1. Windows では、エディタを右クリックし、「管理者として実行」を選択します。
2. c:\windows\system32\drivers\etc\hosts にあるホストファイルを編集し、以下のようにエントリを追加するか更新します。
127.0.0.1 flow.local.rnd.ptc.com
ここで、flow.local.rnd.ptc.com をエイリアスに置き換える必要があります。
前述の手順を実行すると、アプリケーションと、そのアプリケーション用のクライアント ID およびクライアントシークレットが作成されます。
1. 次のコマンドを使用して OAuth コンフィギュレーションを作成します。
c:\test\gmail>flow add oauth gmail
[2018-10-21T16:26:54.398] [INFO] add-oauth - Oauth configuration gmail added successfully.
このコマンドによって、プロジェクトフォルダ内に \auth\oauth\gmail-gmail フォルダが作成されます。このフォルダには config.json ファイルが 1 つ格納されます。
この場合、config.json ファイルはテンプレートであり、Google などの特定の OAuth プロバイダで機能するようにカスタマイズする必要があります。
2. これをテキストエディタまたは統合開発環境で開き、以下で説明する変更を行います。このファイルを正しく編集し、引き続き有効な JSON ファイルとなるようにします。
3. 必要に応じて、カテゴリ、名前、タイトル、アイコンを設定します。アイコンの作成と設定の詳細については、 コネクタへのアイコンの追加のセクションを参照してください。
4. キー oauth2_params_other をサーチし、これを次の値に置き換えます
[
"{\"access_type\":\"offline\"}"
]
5. キー oauth2_params_scope をサーチし、その値を次の JSON 配列に置き換えます。
[
"{\"https://www.googleapis.com/auth/gmail.labels\":\"Manage mailbox labels\"}",
"{\"https://www.googleapis.com/auth/gmail.insert\":\"Insert mail into your mailbox\"}",
"{\"https://www.googleapis.com/auth/gmail.modify\":\"All read/write operations except immediate, permanent deletion of threads and messages, bypassing Trash.\"}",
"{\"https://www.googleapis.com/auth/gmail.readonly\":\"Read all resources and their metadata—no write operations.\"}",
"{\"https://www.googleapis.com/auth/gmail.compose\":\"Create, read, update, and delete drafts. Send messages and drafts.\"}",
"{\"https://www.googleapis.com/auth/gmail.send\":\"Send email on your behalf\"}"
]
env_local_params の値をメモしておきます。ここで、local は環境名です。この環境は 5 つあり、これらはキー env_production_params, env_pre_prod_params, env_staging_params, env_local_params によって表されます。この値は {{{local.CLIENT_SECRET}}} という形式です。local.CLIENT_SECRET は環境名の変数です。これは 3 つの開始括弧と終了括弧で囲む必要があります。ThingWorx Composer で LoadOAuthConfigurationサービスを実行して OAuth を ThingWorx Flow サーバーにロードすると、顧客が指定した値にこれらの値が置き換えられます。これらの値は JSON ファイルから提供されます。この値は、ThingWorx Flow サーバーが動作している環境でのみ、OAuth コンフィギュレーションを生成する際に置換されます。サーバーの NODE_ENV 環境変数が production に設定されている場合、OAuth データファイルで提供されている値が production の値 CLIENT_SECRET に取り込まれます。これにより、顧客先での展開ごとに OAuth コンフィギュレーションをカスタマイズできます。
6. base_url を検索し、その値を https://accounts.google.com/o/oauth2 に置き換えます。
7. oauth2_auth_url を検索し、その値を /auth に置き換えます。
OAuth コンフィギュレーションのテスト
OAuth コンフィギュレーションを展開する前にテストできます。このために ThingWorx Flow CLI はブラウザを起動し、ここでユーザーは自分の資格証明を使用して OAuth プロバイダにサインインできます。認証が成功した場合、アクセストークンが生成され、後から使用するためにこれをディスクに保存できます。埋め込みの Chrome ブラウザウィンドウで適切なコンフィギュレーションを選択することによって、各展開のコンフィギュレーションをテストすることもできます。
テストコマンドを実行する前に、前述のように env_<環境名>_params で置換される実際のクライアント ID とクライアントシークレットが含まれているテストデータファイルを作成する必要があります。このためには、新規 JSON ファイル testOauthData.jsonc:\test 内に作成し、これに次の内容を追加します。
{
"gmail-gmail": {
"Test Gmail Oauth": {
"CLIENT_ID": "<your-client-id-here>"
"CLIENT_SECRET": ""<your-client-secret-here>"
}
}
}
<your-client-id-here><your-client-secret-here> は、前の手順で Google コンソールから取得した値に置き換えてください。
次に、ユーザーのホームディレクトリにある .flow\flow.json ファイルに、正しいホスト名、ポート、認証パスフレーズが含まれていることを確認します。認証パスフレーズは、自己署名証明書の作成中に提供された場合にのみ必要です。
コマンドプロンプトでコマンド set FLOW_ALLOW_UNTRUSTED_CERTIFICATES=true を実行します。
自己署名証明書を使用してツールを実行しているので、この変数が必要です。
1. 次のコマンドを実行して OAuth をテストします。
flow test oauth gmail-gmail -f ..\testOauthData.json -t "Test Gmail Oauth"
2. テストするコンフィギュレーションを選択し、「Validate OAuth Configuration」をクリックします。
3. アプリケーションに対してアクセスを許可するスコープを選択し、「Allow」をクリックします。
4. Google アカウントのユーザー名を入力します。任意の Google アカウントを入力できます。クライアント ID とクライアントシークレットの作成に使用したアカウントである必要はありません。
5. パスワードを入力します。認証に成功すると、アクセストークンが表示されます。
6. 「保存して終了」をクリックして、後から使用するためにアクセストークンを保存します。
次のようなメッセージがコンソールに表示されます。
[2018-10-22T12:51:07.643] [INFO] oauth - Access token saved with ID :664ec37a-9720-460c-8536-fbf372198cb1
このメッセージ内の ID を使用して、検索、操作、トリガーなど、アクセストークンに依存するその他の成果物をテストします。前述の手順で生成された ID を、 -a/--access_token オプションを使用して、すべてのテストコマンドに渡す必要があります。
* 
リダイレクト URI の不一致などのエラーを受け取った場合、flow.json コンフィギュレーションが正しいことと、Flow が使用する URL と Google に登録されている URL が一致していることを確認する必要があります。テストが開始すると、Flow が使用するリダイレクト URL がコンソールに出力されます。
例: [2018-10-22T11:07:53.868] [INFO] oauthServer- Server started, redirect_uri used for oauth = https://flow.local.rnd.ptc.com:443/Thingworx/Oauths/oauth/return
* 
OAuth アクセストークンは一時的であり、アクセストークンを使用して操作、検索、トリガーをテストする前に、Flow の OAuth テストコマンドを実行して新規トークンを再生成する必要があります。
検索の作成
検索はサーチメカニズムです。これらは通常、操作またはトリガーの特定の入力フィールドのオプションのリストを動的に取得するときに使用します。たとえば、Gmail の電子メールメッセージにはラベルが関連付けられていることがあります。これによって、すべてがラベルを使用してタグ付けされている関連電子メールを簡単にサーチできます。ただし、エンドユーザーが各自のアカウントに作成されているすべてのラベルの名前を覚えていることはほとんどありません。ここで構築する検索は、Gmail アカウントで検出されたラベルの ID と値のペアを生成します。それらの 1 つ以上を使用して、それらのラベルが付いた電子メールの ID と件名を取得できます。
検索はメタデータを持たない代わりに、単一の index.js ファイルによって表されます。これらはバージョン管理も行われません。検索メソッドは index.js ファイル内にいくつでも存在できます。
検索を作成するには、次のコマンドを実行します。
c:\test\gmail>flow add lookup
[2018-10-22T14:41:52.298] [INFO] add-lookup - Lookup added successfully
このコマンドを実行すると、lookup\gmail フォルダ内に index.js が生成されます。
統合開発環境で index.js ファイルを開き、以下に示すコードをこのファイルに追加します。
ファイルの先頭で、次のモジュールをインポートします。
const async = require('async')
const request = require('request')
const logger = require('ptc-flow-sdk').getLogger('gmail-lookup')
このファイル内の既存のすべてのコードの後ろに、以下のコードをコピーします。

gmailAPIs.getLabels = function (input, options, output) {
logger.debug('Trying to fetch labels')
// Gmail API to fetch th labels in the gmail account
options.url = 'https://www.googleapis.com/gmail/v1/users/me/labels'
// Validating that the authorization is done and we have a access_token to //make a request else throw the error
options.validateDependencies(input.access_token, function (err, status) {
if (err) {
return output({
error: err
})
}
// If the authorization is proper then execute the request
execute(input, options, output)
})
}
// common function for api to execute the request module
function execute (input, options, output) {
async.waterfall([
function (cb) {
// In input we get auth code which we can use to get access token
getAccessToken(input, options, cb)
}
], function (err, accessToken) {
if (err) {
return output({
error: err
})
} else {
// Execute the request to get the labels from the gmail api
requestExecute(input, accessToken, options, output)
}
})
}
// Extract the acces_token from the input and return it
function getAccessToken (input, options, cb) {
options.getAccessToken(input.access_token, function (err, oauth) {
if (err) {
cb(err)
} else {
oauth = JSON.parse(oauth)
cb(null, oauth.access_token)
}
})
}
// Make a request to the gmail url to get the labels
function requestExecute (input, accessToken, options, output) {
request({
method: 'GET',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
url: options.url
}, function (err, res, body) {
let result = []
if (err) {
return output({
error: err
})
}
if (res.statusCode === 401) {
return output({
error: 'Your access token is Invalid or Expired'
})
}
if (res.statusCode >= 200 && res.statusCode < 400) {
if (typeof (body) === 'string') {
body = JSON.parse(body)
}
result = filterResult(body.messages || body.labels || body, input)
var pageDetails = options.getPage(result, input, options)
var data = {
'results': result.slice(pageDetails.page, (pageDetails.page + options.maxResults))
}
data.next_page = options.getNextPage(data.results.length >= options.maxResults)
return output(null, data)
}
return output({
error: body
})
})
}
// filter result on the basis of output demand
function filterResult (body, input) {
var result = []
if (body && Array.isArray(body)) {
body.forEach(function (item, index) {
result.push({
'id': String(item.name),
'value': item.name
})
})
}
return result
}
検索をテストするには、次のコマンドを実行します。
1. 以下のコマンドを使用して新規アクセストークンを取得します。
flow test oauth gmail-gmail -f ..\testOauthData.json -t "Test Gmail Oauth"
2. トークンを保存して終了します。
3. 以下のコマンドを使用して検索をテストします。
flow test lookup gmail getLabels -a cecd33a3-8a33-4c0c-b298-178fd80a9261 -l trace. 検索によって生成された出力が表示されます。この出力は ID と値の JSON 配列です。
操作の作成とテスト
操作は接続された外部システムと対話してなんらかの処理を実行します。通常、これは作成、読み取り、更新、削除処理です。操作は入力をとり、なんらかの出力を生成します。操作の入力および操作によって生成される出力を action.json ファイルで指定する必要があります。入力と出力のプロパティは入力フォームのレンダリングに使用される特別な JSON スキーマであり、出力スキーマを使用してマッピングユーザーインタフェースがレンダーされます。その他の便利なプロパティとしては、操作のグループ化に使用される tag や、ユーザーインタフェースに操作のアイコンを表示するために使用される icon があります。
新規操作を作成するには、以下のコマンドを実行します。
c:\test\gmail>flow add action get-messages
[2018-10-22T16:26:53.925] [INFO] add-action - Action get-messages, version v1 added successfully
次に、統合開発環境で action.json ファイル C:\test\gmail\action\gmail-get-messages\v1\action.json を開きます。
入力およびアイコンのプロパティを gmail に設定します。入力プロパティの JSON スキーマは、次のコードに示すようになります。
Set the input property to {
"title": "Get email messages",
"type": "object",
"properties": {
"auth": {
"title": "Authorize gmail",
"type": "string",
"oauth": "gmail-gmail",
"minLength": 1
},
"label": {
"title": "Label",
"type": "string",
"minLength": 1,
"lookup": {
"id": "getLabels",
"service": "gmail",
"enabled": true,
"searchable": false,
"auth": "oauth",
"dependencies": [
"auth"
]
}
}
}
}
入力スキーマで単一の入力フィールドが定義されています。これは検索が指定されているのでリストです。フローコンポーザで使用した場合、検索が実行され、返された値がリストに表示されます。検索の依存がどのように定義されているかについて注意してください。これはシステムに対して、検索を呼び出す前に認証フィールドに入力する必要があることを通知しています。
認証プロパティはこの操作によって使用される認証メソッドを定義します。この場合、OAuth コンフィギュレーション Gmail を使用します。
Set the “output” property to {
"messages": {
"title": "Messages",
"type": "array",
"items": {
"type": "object",
"properties": {
"messageId": {
"type": "string",
"title": "Message Detail ID"
},
"subject": {
"type": "string",
"title": "Message Detail Sub"
}
}
}
}
}
* 
この操作によって生成される出力は JSON オブジェクトの JSON 配列です。各オブジェクトが messageId フィールドと subject フィールドを持ちます。
統合開発環境で index.js ファイルを開きます。ファイルの先頭に、以下のコードを追加します。
const rp = require('request-promise')
const logger = require('ptc-flow-sdk').getLogger('gmail-get-messages')
execute メソッドを以下のコードに置き換えます。
this.execute = function (input, output) {
// Create a request header to get messages under a label selected from
const options = {
method: 'GET',
url: 'https://www.googleapis.com/gmail/v1/users/me/messages',
useQuerystring: true,
qs: {labelIds: ['STARRED']},
headers:
{
'Authorization': 'Bearer ' + input.auth,
'Content-Type': 'application/json'
}
}
rp(options).then((rawData) => {
const data = JSON.parse(rawData)
let mailRequests = []
if (data && data.messages) {
data.messages.forEach((msg) => {
mailRequests.push(this.fetchMessage(msg.id, input.auth))
})
return Promise.all(mailRequests)
} else {
logger.warn('No messages found')
Promise.resolve()
}
}).then((results) => {
if (results) {
let arr = []
results.forEach((result) => {
let resData = JSON.parse(result)
let msgHeader = resData.payload.headers.find(header => header.name === 'Subject')
arr.push({messageId: resData.id, subject: msgHeader ? msgHeader.value : 'No subject'})
})
return output(null, {messages: arr})
} else {
return output(null)
}
}).catch(err => {
return output(err)
})
}
以下に示す新規メソッドを追加します。
this.fetchMessage = function (msgId, authToken) {
const options = {
method: 'GET',
url: 'https://www.googleapis.com/gmail/v1/users/me/messages/' + msgId,
qs: { format: 'metadata', metadataHeaders: 'Subject' },
headers:
{
'Authorization': 'Bearer ' + authToken,
'Content-Type': 'application/json'
}
}
return rp(options)
}
このファイルが有効な JavaScript ファイルであることを確認します。
1. 次の手順を使用して、アクセストークンを再び取得します。
FLOW_ALLOW_UNTRUSTED_CERTIFICATES=true を設定します
以下のコマンドを実行し、返された ID をメモしておきます。
flow test oauth gmail-gmail -f ..\testOauthData.json -t "Test Gmail Oauth"
2. 新規 JavaScript ファイル C:\test\gmail\test\actionTestData.js を作成し、次のコードをこれに追加して保存します。
module.exports = {
testInput: {
label: 'STARRED'//use a label that applies to a few emails.
},
testOutputFn: function (input, actualOutput) {
// validate the actualOutput against expected output
// return a rejected promise to fail the validation or a resolved promise for success
// return Promise.reject(new Error('Validation successful'))
return Promise.reject(new Error('Validation failed'))
}
}
* 
-i/--input および -o/--output パラメータは、promise を返すデータまたは関数をとります。
これがサーバー上で実行された場合、入力パラメータの一部としてラベルを使用でき、input.label としてアクセスできます。テストユーティリティは検索を実行しないので、検索の出力をテストユーティリティに渡す必要があります。
3. 次のようなテストコマンドを実行します。
C:\test\gmail>flow test action gmail-get-messages -a 685b7377-7000-
4a92-8679-8630c68a3265 -l debug -i testInput -f
C:\test\gmail\test\actionTestData.js -o testOutput
The test run should succeed.
ポーリングのトリガーの作成とテスト
1. 新しいポーリングのトリガーを作成するには、次のコマンドを実行します。
flow add trigger -p
[2019-02-28T17:03:23.823] [INFO] add-trigger - Trigger gmail, version v1 added successfully
2. IDE で、C:\test\gmail\trigger\poll\gmail \v1\trigger.json にある trigger.json ファイルを開きます。
3. gmail のアイコンプロパティを次のように設定します。
"icon": "gmail",
4. 入力と出力のプロパティを設定します。

Set the input property to
{
"properties": {
"auth": {
"type": "string",
"title": "Authorize gmail",
"minLength": 1,
"oauth": "gmail-gmail",
"propertyOrder": 1
},
"search": {
"type": "string",
"title": "Search Text",
"propertyOrder": 2,
"description": "Enter the search text to search for a specific email. E.g., from:john or subject:Christmas"
},
"customFilters": {
"type": "array",
"propertyOrder": 5,
"title": "Custom Filters",
"items": {
"type": "object",
"title": "Filter",
"properties": {
"input": {
"type": "string",
"title": "Input",
"minLength": 1
},
"operator": {
"type": "string",
"title": "Condition",
"enum": [
"Equals",
"GreaterThan"
],
"enumNames": [
"Equals",
"Greater Than"
]
},
"expected": {
"type": "string",
"title": "Expected",
"minLength": 1
}
}
}
}
},
"oneOf": [
{
"type": "object",
"title": "New Email",
"description": "Triggers when a new email is received",
"properties": {
"event": {
"type": "string",
"readonly": true,
"enum": [
"new_mail"
],
"options": {
"hidden": true
},
"propertyOrder": 3
},
"label": {
"type": "string",
"title": "Label",
"propertyOrder": 4,
"description": "Select a label for which you wish to set a trigger. E.g., If you select label as ‘Trash’, the trigger will fire off every time a new mail is moved to label named ‘Trash’ in your Gmail account."
}
}
},
{
"type": "object",
"title": "New Attachment",
"description": "Triggers when a new attachment is received",
"properties": {
"event": {
"type": "string",
"readonly": true,
"enum": [
"new_attachment"
],
"options": {
"hidden": true
},
"propertyOrder": 3
},
"label": {
"type": "string",
"title": "Label",
"propertyOrder": 4,
"description": "Select a label for which you wish to set a trigger. E.g., If you select label as ‘Trash’, the trigger will fire off every time a new mail is moved to label named ‘Trash’ in your Gmail account."
}
}
}
]
}
入力スキーマで単一の入力フィールドが定義されています。oneOf オブジェクトは、トリガーによってサポートされるイベントを定義します。上記のスキーマは、2 つのトリガーイベントを定義します。
新規電子メール
新規添付ファイル
認証プロパティは、このトリガーによって使用される認証メソッドを説明します。この場合、OAuth コンフィギュレーション Gmail を使用します。
Set the “output” property to
{
"new_mail": {
"type": "object",
"properties": {
"messageId": {
"type": "string",
"title": "ID",
"displayTitle": "ID"
},
"subject": {
"title": "Subject",
"displayTitle": "Subject",
"type": "string"
}
}
},
"new_attachment": {
"type": "object",
"properties": {
"attachments": {
"title": "Attachments",
"displayTitle": "Attachments",
"type": "array",
"items": {
"type": "object",
"properties": {
"mimeType": {
"title": "Mime Type",
"displayTitle": "Mime Type",
"type": "string"
},
"filename": {
"title": "File Name",
"displayTitle": "File Name",
"type": "string"
},
"attachmentId": {
"title": "Attachment ID",
"displayTitle": "Attachment ID",
"type": "string"
}
}
}
}
}
}
}
上記の出力スキーマは、トリガー入力スキーマで定義された 2 つのトリガーイベントの出力プロパティーを定義します。
1. IDE で index.js ファイルを開き、ファイルの先頭に次のコードを追加します。
const rp = require('request-promise')
const logger = require('ptc-flow-sdk').getLogger('gmail-trigger')
2. execute メソッドを以下のコードに置き換えます。
Trigger.execute = function (input, options, output) {
// Create a request header to get messages under a label selected from
var date = new Date(options.unixTime * 1000)
const httpOpts = {
method: 'GET',
url: 'https://www.googleapis.com/gmail/v1/users/me/messages',
useQuerystring: true,
qs: { q: 'newer:' + date.getFullYear() + '/' + date.getMonth() + '/' + date.getDay() },
headers:
{
'Authorization': 'Bearer ' + input.auth,
'Content-Type': 'application/json'
}
}
rp(httpOpts).then((rawData) => {
const data = JSON.parse(rawData)
let mailRequests = []
if (data && data.messages) {
data.messages.forEach((msg) => {
mailRequests.push(this.fetchMessage(msg.id, input.auth))
})
return Promise.all(mailRequests)
} else {
logger.warn('No messages found')
Promise.resolve()
}
}).then((results) => {
if (results) {
let arr = []
results.forEach((result) => {
let resData = JSON.parse(result)
let msgHeader = resData.payload.headers.find(header => header.name === 'Subject')
arr.push({ messageId: resData.id, subject: msgHeader ? msgHeader.value : 'No subject' })
})
return output(null, { messages: arr })
} else {
return output(null)
}
}).catch(err => {
return output(err)
})
}
3. 以下に示す新規メソッドを追加します。
Trigger.fetchMessage = function (msgId, authToken) {
const options = {
method: 'GET',
url: 'https://www.googleapis.com/gmail/v1/users/me/messages/' + msgId,
qs: { format: 'metadata', metadataHeaders: 'Subject' },
headers:
{
'Authorization': 'Bearer ' + authToken,
'Content-Type': 'application/json'
}
}
return rp(options)
}
* 
このファイルが有効な JavaScript ファイルであることを確認します。
アクセストークンの取得
アクセストークンを再度取得するには、次の手順を実行します。
1. 次のプロパティを設定します: FLOW_ALLOW_UNTRUSTED_CERTIFICATES=true
2. 以下のコマンドを実行し、返された ID をメモしておきます。
flow test oauth gmail-gmail -f ..\testOauthData.json -t "Test Gmail Oauth"
3. 次のようなテストコマンドを実行します。
flow test trigger gmail execute -p -e new_mail -a e0d56340-2fc4-4618-931c-ad6c983ae0e5 --stopAfter 1 --unixTime 1551312000
コネクタへのアイコンの追加
1. コネクタプロジェクト内に common フォルダを作成します。
2. common フォルダの下に、css という名前のフォルダを作成します。
3. 次のフォーマットで JSON ファイルを追加します。
{ "name": "connector-name",
"background": "#FFFFFF",
"png128pxBase64": "base64encodedbinarydata"
}
name プロパティにはコネクタの名前を指定し、metadata json ファイルでの操作の icon プロパティと一致していなければなりません。
背景には例に示すように HEX カラーコードを指定します。
アイコンイメージは .PNG フォーマットを使用し、バイナリデータは base64 でエンコードされている必要があります。詳細については、インターネットで、PNG を base64 でエンコードされたバイナリ表現に変換する方法についてサーチしてください。