ThingWorx Flow > ThingWorx Flow SDK > 부록 B: ThingWorx Flow 커넥터 SDK 자습서
부록 B: ThingWorx Flow 커넥터 SDK 자습서
사전 요구 사항
다음은 이 자습서에 필요한 사전 요구 사항입니다.
LTS 버전 Node.js 8.9.0 + 설치 관리자
Node js 프로젝트를 처리할 수 있는 IDE(통합 개발 환경)
자습서에서는 WebStorm이 IDE로 사용됩니다.
Node js 코드에 대한 중급 수준의 이해
샘플 폴더
소개
자습서는 일반적인 커넥터를 작성하는 데 필요한 단계를 설명합니다. 대부분의 개발자가 Gmail 작동 방식에 친숙하므로 Gmail용 커넥터를 작성해 보겠습니다. 커넥터 작성을 통해 커넥터 작성과 관련된 도구, 아티팩트 및 프로세스를 숙지하고 사용자 응용 프로그램에 필요한 커넥터를 작성할 수 있습니다. 새 커넥터를 작성하기 위해 ThingWorx Flow를 배포할 필요가 없습니다. 커넥터를 로컬로 작성하고 테스트한 후에는 테스트를 위해 이를 테스트 온프레미스 설치에 배포할 수 있습니다.
이 자습서에서는 다음을 다룹니다.
1. 커넥터 프로젝트 만들기
2. OAuth2 구성
3. Gmail 계정에서 관련된 필터를 검색하는 조회 만들기
4. 선택한 필터와 일치하는 이메일 메시지의 ID 및 제목을 가져오는 작업 만들기
5. 새 메일이 수신될 때 새 흐름을 시작하는 트리거 만들기
6. 아이콘 추가
7. ThingWorx Flow의 온프레미스 인스턴스에 커넥터 배포
커넥터 프로젝트 만들기
커넥터는 OAuth 구성, 작업, 조회, 트리거와 같은 다양한 아티팩트로 구성된 특수 NPM 패키지입니다. 프로젝트는 NPM 패키지를 작성하는 패턴을 따라야 합니다. 프로젝트에는 package.json, lib 폴더, 테스트 폴더 및 각 아티팩트와 해당 버전용 폴더가 있어야 합니다.
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. IDE에서 프로젝트 디렉터리를 열어 기본적으로 작성된 아티팩트를 검토합니다.
모든 프로젝트에는 index.js 파일과 package.json 파일이 포함되어 있습니다. ThingWorx Flow 서버에서 커넥터를 로드하기 위해 node.js 파일이 필요하기 때문에 이 파일을 변경하지 마십시오.
* 
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 파일 하나만 있습니다.
이 경우 config.json 파일은 Google과 같은 특정 OAuth 공급자와 함께 작동하도록 사용자 정의해야 하는 템플릿입니다.
2. 텍스트 편집기 또는 IDE에서 이 파일을 열고 아래 설명대로 변경합니다. 파일을 올바르게 편집했고 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은 환경의 이름입니다. 다섯 가지 환경이 가능하며 env_production_params, env_pre_prod_params, env_staging_params, env_local_params 키로 표시됩니다. 값의 형식은 {{{local.CLIENT_SECRET}}}입니다. local.CLIENT_SECRET은 환경의 이름을 나타내는 변수입니다. 이러한 변수는 세 개의 여는 중괄호와 닫는 중괄호로 묶어야 합니다. 이러한 값은 OAuth를 ThingWorx Flow 서버에 로드하기 위해 ThingWorx Composer에서 LoadOAuthConfiguration 서비스를 실행하는 동안 고객이 제공한 값으로 바뀝니다. 값은 JSON 파일을 통해 제공됩니다. ThingWorx Flow 서버가 실행 중인 환경에서만 OAuth 구성을 생성할 때 값이 대체됩니다. 서버에 NODE_ENV 환경 변수가 생산으로 설정된 경우 생산 값 CLIENT_SECRET가 OAuth 데이터 파일에 제공된 값으로 채워집니다. 따라서 각 고객 배포에 대해 OAuth 구성을 사용자 정의할 수 있습니다.
6. base_url을 찾아서 해당 값을 https://accounts.google.com/o/oauth2로 바꿉니다.
7. oauth2_auth_url을 찾아서 해당 값을 /auth로 바꿉니다.
OAuth 구성 테스트
OAuth 구성을 배포하기 전에 테스트할 수 있습니다. 이를 수행하려면 ThingWorx Flow CLI에서 브라우저를 시작하고 자격 증명을 사용하여 OAuth 공급자에 로그인합니다. 인증에 성공하면 액세스 토큰이 생성되고 나중에 사용할 수 있도록 디스크에 저장할 수 있습니다. 포함된 Chrome 브라우저 창에서 적절한 구성을 선택하여 각 배포 구성을 테스트할 수도 있습니다.
테스트 명령을 실행하려면 먼저 위에서 언급한 대로 env_<environment-name>_params를 대체할 실제 클라이언트 ID와 보안 키가 포함된 테스트 데이터 파일을 작성해야 합니다. 이를 수행하려면 c:\test에서 새 JSON 파일인 testOauthData.json 파일을 만들고 해당 파일에 다음 콘텐츠를 추가합니다.
{
"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. 테스트할 구성을 선택하고 OAuth 구성 유효성 검사를 클릭합니다.
3. 액세스할 응용 프로그램을 허용할 범위를 선택하고 허용을 클릭합니다.
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는 조회, 작업, 트리거 등 액세스 토큰에 종속된 다른 아티팩트를 테스트하는 데 사용됩니다. -a/--access_token 옵션을 사용하여 모든 테스트 명령에 위에서 작성된 ID를 제공해야 합니다.
* 
리디렉션 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 test oauth 명령을 실행하여 새 토큰을 재생성해야 합니다.
조회 만들기
조회는 검색 메커니즘입니다. 조회는 일반적으로 작업 또는 트리거의 특정 입력 필드에 대한 옵션 목록을 동적으로 가져오는 데 사용됩니다. 예를 들어, Gmail의 이메일 메시지에 레이블이 연관되어 있을 수 있습니다. 이 경우 해당 레이블을 사용하여 모든 태그가 지정된 관련 이메일을 빠르게 검색할 수 있습니다. 그러나 최종 사용자는 계정에 작성된 모든 레이블의 이름을 기억하기가 쉽지 않습니다. 여기서 작성하는 조회는 Gmail 계정에 있는 레이블에 대해 ID-값 쌍을 생성합니다. 이러한 ID-값 쌍 중 하나 이상을 사용하여 해당 레이블이 있는 이메일의 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가 생성됩니다.
IDE에서 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 파일에 지정되어야 합니다. input 및 output 속성은 입력 양식을 렌더링하는 데 사용되는 특수 JSON 스키마이고, 출력 스키마는 매핑 사용자 인터페이스를 렌더링하는 데 사용됩니다. 다른 유용한 속성에는 작업을 그룹화하고 작업의 아이콘을 사용자 인터페이스에 표시하는 데 사용되는 태그와 아이콘이 포함되어 있습니다.
새 작업을 만들려면 아래 명령을 실행합니다.
c:\test\gmail>flow add action get-messages
[2018-10-22T16:26:53.925] [INFO] add-action - Action get-messages, version v1 added successfully
그런 다음 IDE에서 C:\test\gmail\action\gmail-get-messages\v1\action.json에 있는 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"
]
}
}
}
}
입력 스키마는 단일 입력 필드를 정의합니다. 이는 필드에 조회가 지정되어 있으므로 목록입니다. Flow Composer에서 사용되면 조회가 실행되고 반환된 값이 목록에 표시됩니다. 조회의 종속성이 설명되는 방식을 확인하십시오. 시스템에 조회를 호출하기 전에 auth 필드를 채워야 함을 알립니다.
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 배열입니다. 각 객체에는 messageIdsubject 필드가 있습니다.
IDE에서 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 객체는 트리거에서 지원하는 이벤트를 정의합니다. 위 스키마는 두 개의 트리거 이벤트를 정의합니다.
새 이메일
새 첨부 파일
auth 속성은 이 트리거에 사용되는 인증 방법을 설명합니다. 이 경우 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"
}
}
}
}
}
}
}
위 출력 스키마는 트리거 입력 스키마에 정의된 두 개의 트리거 이벤트에 대한 출력 속성을 정의합니다.
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 속성과 일치해야 합니다.
다음 예와 같이 배경은 16진수 색상 코드여야 합니다.
아이콘 이미지는 .PNG 형식이어야 하고 바이너리 데이터는 base64 형식으로 인코딩되어야 합니다. 자세한 내용을 보려면 인터넷에서 PNG를 base64 형식으로 인코딩된 바이너리 표현으로 변환하는 방법을 검색하십시오.