This repository has been archived by the owner on Jan 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
875 lines (796 loc) · 26.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
'use strict'
/**
* Watson Work Services SDK
* @module watsonworkspace-sdk
*/
const EventEmitter = require('events')
const fs = require('fs')
const graphql = require('./graphql')
const imageSize = require('image-size')
const mime = require('mime-types')
const request = require('request-promise')
const logger = require('winston')
const oauth = require('./oauth')
const path = require('path')
const Promise = require('bluebird')
const ui = require('./ui')
const baseUrl = 'https://api.watsonwork.ibm.com'
// controls the request-promise logging level; logs the raw req/res data
require('request-debug')(request, (type, data, r) => {
if (logger.level === 'debug') {
logger.debug(JSON.stringify(data, null, 2))
}
})
/**
* A Watson Work Services App (SDK instance).
* @class
*/
module.exports = class SDK extends EventEmitter {
constructor (appId, appSecret, token) {
super()
this.appId = appId
this.appSecret = appSecret
this.token = token
}
/**
* Picks an object from server response, which is a Promise. If a response is { space : {displayName: "foo"} },
* pick('space') returns {displayName: "foo"}.
* @param {string} property Fields returned in user informatation e.g. id, displayName, email
* @returns {Promise<Object>} Promise containing the picked object
*/
pick (property, promise) {
return new Promise((resolve, reject) => {
promise.then(response => {
// guard against the response being a raw string
if (typeof response === 'string') {
logger.warn(`Can not find '${property}'; converting to JSON`)
response = JSON.parse(response) // convert to JSON for picking
}
// check if the property is present
if(response[property] === undefined) {
console.error(`No '${property}' field in ${JSON.stringify(response, null, 2)}`)
}
resolve(response[property])
})
.catch(err => reject(err))
})
}
/**
* Fulfills a Promise and calls map() of the items defined by the property.
* @param {string} property The property containing a collection
* @param {function} fn The function to apply in map()
* @param {Promise<Object>} promise Promise returned from a server response
* @returns {Promise<Object>} Promise containing the updated data
*/
map (property, fn, promise) {
return new Promise((resolve, reject) => {
promise.then(response => {
if (response[property]) {
response[property] = response[property].map(fn)
} else {
logger.warn(`Map requested on missing property '${property}'`)
}
resolve(response)
})
.catch(err => reject(err))
})
}
/**
* Converts a JSON string to an object.
* @param {string} obj String to convert
* @returns {Object} Converted object
*/
jsonify (obj) {
return JSON.parse(obj)
}
/**
* Authenticates the SDK with Watson Work Services. The resulting JWT token will be stored
* for subsequent use. The token can be obtained from the Promise, but it is not necessary.
* If a faiure occurs, the process will re-attempt every second for ten tries.
* The JWT token will be refreshed automatically based on the expiration set in the response.
* @returns {Promise<string>} Promise containing the app's JWT token
*/
authenticate () {
return new Promise((resolve, reject) => {
const retry = 10000
let errors = 0
if (this.appId === undefined || this.appSecret === undefined ||
this.appId.length !== 36 || this.appSecret.length !== 28) {
reject(new Error(`appId ${this.appId} or appSecret has a problem`))
} else {
oauth.run(
this.appId,
this.appSecret,
(err, token) => {
if (err) {
logger.error(`Failed to get JWT token; retrying in ${retry / 1000} seconds`)
errors++
if (errors > 10) {
reject(new Error(`Too many JWT token attempts giving up`))
}
setTimeout(this.authenticate, retry)
return
}
if (this.token) {
logger.verbose('Refreshed access token')
}
this.token = token()
resolve(token())
})
}
})
}
/**
* Sends GraphQL to Watson Work Services. The GraphQL can either be the raw string or JSON format.
* @param {string|Object} graphql The GraphQL query or mutation
* @returns {Promise<Object>} Promise containing the server response
*/
sendGraphql (graphql) {
const headers = {
'Content-Type': typeof graphql === 'string' ? 'application/graphql' : 'application/json',
'x-graphql-view': 'PUBLIC, BETA, EXPERIMENTAL'
}
return this.pick('data', this.sendRequest(`graphql`, 'POST', headers, graphql))
}
/**
* Sends a request to Watson Work Services.
* If a POST body is set, it will be checked whether it is a string or Object.
* If the body is an Object, the response is assumed to also be JSON.
* @param {string} route The route e.g. spaces
* @param {string} method HTTP method e.g. GET or POST
* @param {Object} headers HTTP headers
* @param {string|Object} [body] Optional HTTP body if POSTing
* @returns {Promise<Object>} Promise containing the server response
*/
sendRequest (route, method, headers, body) {
// add the auth header for convenience
headers.Authorization = `Bearer ${this.token}`
const options = {
method: method,
uri: `${baseUrl}/${route}`,
headers: headers,
body: body,
json: (typeof body) === 'object',
resolveWithFullResponse: false
}
logger.verbose(`${method} to '${route}'`)
return request(options)
}
/**
* Retrieves user configuration data.
* @param {string} configurationToken The configuration token sent by Watson Work Services
* @returns {Promise<Object>} Promise containing the configuration data
*/
getConfigurationData (configurationToken) {
return this.sendRequest(
`v1/apps/${this.appId}/configurationData/${configurationToken}`, 'GET', {})
}
/**
* Get information about a person.
* @param {string[]} fields Fields returned in user informatation e.g. id, displayName, email
* @returns {Promise<Object>} Promise containing the person object
*/
getMe (fields) {
const json = {
query: graphql.getMe(fields)
}
return this.pick('me', this.sendGraphql(json))
}
/**
* Get information about a message.
* @param {string} id Message ID e.g. 5a79f65de4b0d880b508ed57
* @param {string[]} fields Fields returned in the message e.g. id, content, annotations
* @returns {Promise<Object>} Promise containing the message object
*/
getMessage (id, fields) {
const json = {
query: graphql.getMessage(fields),
variables: {
id: id
}
}
return this.map('annotations', this.jsonify, this.pick('message', this.sendGraphql(json)))
}
/**
* Get information about a space such as membership.
* @param {string} id Space ID e.g. 57cf270ee4b06c8b753629e6
* @param {string[]} fields Fields returned in space informatation
* @returns {Promise<Object>} Promise containing the space object
*/
getSpace (id, fields) {
const json = {
query: graphql.getSpace(fields),
variables: {
id: id
}
}
return this.pick('space', this.sendGraphql(json))
}
/**
* Download a file
* @param {*} fileId
* @returns {Promise<Object>} Promise containing the file stream
*/
getFile (fileId) {
return new Promise((resolve, reject) => {
let uri = `${baseUrl}/files/api/v1/files/file/${fileId}`;
let options = {
method: 'GET',
uri: uri,
headers: {
Authorization: `Bearer ${this.token}`
}
};
request(options)
.then(result => {
let json = JSON.parse(result)
let resourceurl = json.entries[0].urls.redirect_download
const dlResourceOptions = {
url: resourceurl,
headers: {
Authorization: `Bearer ${this.token}`
},
encoding: null
}
request(dlResourceOptions)
.then(body => {
resolve(body)
})
.catch(err => {
reject(err)
});
})
.catch(err => {
reject(err)
});
});
}
/**
* Sends a file into a space. If the file is an image, the width and height can
* be optionally specified. If omitted, the width and height will reflect the
* full size. For all other files, the mime-type will inferred on a best effort.
* @param {string} spaceId Space ID e.g. 57cf270ee4b06c8b753629e6
* @param {string} file Full path to the file
* @param {number} [width] Optional width to set if file is an image
* @param {number} [height] Optional height to set if file is an image
* @returns {Promise<Object>} Promise containing the space object
*/
sendFile (spaceId, file, width, height) {
logger.verbose(`Sending file '${file}' to conversation '${spaceId}'`)
let uri = `${baseUrl}/v1/spaces/${spaceId}/files`
const mimeType = mime.contentType(path.extname(file))
if (width && height) {
uri += `?dim=${width}x${height}`
} else {
const isImage = mimeType.toLowerCase().includes('image/')
if (isImage) {
// figure out the dimensions and send full size
const dim = imageSize(file)
uri += `?dim=${dim.width}x${dim.height}`
}
}
const options = {
method: 'POST',
uri: uri,
headers: {
Authorization: `Bearer ${this.token}`,
'content-type': 'multipart/form-data'
},
resolveWithFullResponse: false,
formData: {
file: {
value: fs.createReadStream(file),
options: {
filename: path.parse(file).base,
contentType: mimeType
}
}
}
}
return request(options)
}
/**
* Similar to sendFile above, but uses a stream instead of a file from the file system.
* If the file is an image, the width and height can
* be optionally specified. If omitted, the width and height will reflect the
* full size. For all other files, the mime-type will inferred on a best effort.
* @param {string} spaceId Space ID e.g. 57cf270ee4b06c8b753629e6
* @param {string} fileStream a stream of the file contents
* @param {string} fileName the name of the file
* @param {string} mimeType the mime type of the file
* @returns {Promise<Object>} Promise containing the space object
*/
sendFileStream (spaceId, fileStream, fileName, mimeType) {
logger.verbose(`Sending file stream to conversation '${spaceId}'`)
let uri = `${baseUrl}/v1/spaces/${spaceId}/files`
const isImage = mimeType.toLowerCase().includes('image/')
if (isImage) {
// figure out the dimensions and send full size
const dim = imageSize(fileStream)
uri += `?dim=${dim.width}x${dim.height}`
}
const options = {
method: 'POST',
uri: uri,
headers: {
Authorization: `Bearer ${this.token}`,
'content-type': 'multipart/form-data'
},
resolveWithFullResponse: false,
formData: {
file: {
value: fileStream,
options: {
filename: fileName,
contentType: mimeType
}
}
}
}
return request(options)
}
/**
* Sends a text message into a space.
* @param {string} spaceId Space ID e.g. 57cf270ee4b06c8b753629e6
* @param {string|Object|Array} content Content to be sent
* @returns {Promise<Object>} Promise containing the message
*/
sendMessage (spaceId, content) {
logger.verbose(`Sending message to conversation '${spaceId}'`)
const body = {
type: 'appMessage',
version: '1',
annotations: []
}
// determine the type of content the user is tying to send
const type = typeof content
switch (type) {
case 'string':
body.annotations.push(ui.message(content))
break
case 'object':
if (Array.isArray(content)) {
body.annotations = content
} else {
body.annotations = [content]
}
break
default:
logger.error(`Error sending message of type '${type}'`)
}
return this.sendRequest(`v1/spaces/${spaceId}/messages`, 'POST', {}, body)
}
/**
* An alternative way to send a text message to a space.
* @param {string} spaceId Space ID e.g. 57cf270ee4b06c8b753629e6
* @param {string} content Content to be sent
* @returns {Promise<Object>} Promise containing the message
*/
sendSynchronousMessage (spaceId, content) {
const json = {
query: graphql.createSynchronousMessage,
variables: {
input: {
conversationId: spaceId,
content: content
}
}
}
return this.sendGraphql(json)
}
/**
* Adds a member to a space.
* @param {} spaceId Space ID e.g. 57cf270ee4b06c8b753629e6
* @param {string[]} memberIds Array of member IDs e.g. 3c845f47-c56a-4ca9-a1cb-12dbebd72c3b
* @returns {Promise<Object>} Promise containing the updated space
*/
addMember (spaceId, memberIds) {
const json = {
query: graphql.addMember,
variables: {
input: {
id: spaceId,
members: memberIds,
memberOperation: 'ADD'
}
}
}
return this.pick('updateSpace', this.sendGraphql(json))
}
/**
* Adds a focus to a specific message. The message must contain content.
* If the message is obtained from getMessage(), ensure the content field is set.
* @param {Object} message The message returned from getMessage() or a webhook
* @param {string} phrase The phrase to add the message (it must be present in content)
* @param {string} lens The lens name to be added
* @param {string} category The category for the lens
* @param {string[]} actions The actions that can be taken e.g. ['commit-code']
* @param {*} [payload] Data to be persisted in the focus and passed to receivers
* @param {*} [hidden] True if hidden from Moments
* @returns {Promise<Object>} Promise containing the updated message
*/
addMessageFocus (message, phrase, lens, category, actions, payload, hidden) {
let id
let pos = -1
if (message.id) {
id = message.id
} else {
id = message.messageId
}
// the message's content differs based on how the message was created
if (message.annotations && message.annotations[0].type === 'generic') {
// app created
pos = message.annotations[0].text.indexOf(phrase)
} else {
// user created
pos = message.content.indexOf(phrase)
}
logger.verbose(`Adding message focus to message '${id}'`)
const json = {
query: graphql.addMessageFocus,
variables: {
input: {
messageId: id,
messageFocus: {
phrase: phrase,
lens: lens,
category: category,
actions: actions,
confidence: 0.99,
payload: payload ? JSON.stringify(payload) : '',
start: pos,
end: pos + phrase.length,
version: 1,
hidden: hidden || false
}
}
}
}
return this.sendGraphql(json)
}
/**
* Sends a targetted message (action fulfillment) to a user.
* @param {string} userId The user's ID e.g. 3c845f47-c56a-4ca9-a1cb-12dbebd72c3b
* @param {Object} annotation The annotation obtained from the 'actionSelected' event
* @param {Object[]} items UI items to be added to the resulting dialog
* @returns {Promise<Object>} Promise containing the updated message
*/
sendTargetedMessage (userId, annotation, items) {
logger.verbose(`Sending targeted message to user ${userId}`)
const input = {
conversationId: annotation.conversationId,
targetUserId: userId,
targetDialogId: annotation.targetDialogId
}
if (!Array.isArray(items)) {
items = [items]
}
if (items.length === 0) {
logger.error(`Targetted message has no annotations or attachments for ${userId}`)
}
// check the type of user interface
if (items.length && items[0].genericAnnotation) {
input.annotations = items
} else {
input.attachments = items
}
const json = {
query: graphql.createTargetedMessage,
variables: {
input: input
}
}
return this.sendGraphql(json)
}
/**
* Extracts the AlchemyAPI data (i.e. entities, keywords, concepts, ...) into a
* single object.
* @param {Object} message Message containing annotation data
* @returns {Object} Object containing AlchemyAPI data
*/
extractInformation (message) {
const messageAnnotations = message.annotations // already converted to JSON
const nlp = {
keywords: [],
entities: [],
concepts: [],
taxonomy: [],
dates: [],
docSentiment: {},
relations: []
}
if (messageAnnotations) {
// pluck out cognitive data
messageAnnotations.forEach(annotation => {
const annotationType = annotation.type
// 'message-nlp-keywords' -> 'keywords'
const shortened = annotationType.substring(annotationType.lastIndexOf('-') + 1)
// only handle Alchemy annotations (ie disregard a message-focus)
if (nlp[shortened]) {
if (shortened === 'docSentiment') {
nlp[shortened] = annotation[shortened]
} else {
nlp[shortened] = (annotation[shortened])
}
}
})
} else {
console.warn(`Information extraction on message with undefined annotations`)
}
return nlp
}
/**
* Uploads a JPEG photo to a user's or app's profile.
* @param {string} file The full path to the file.
* @returns {Promise<Object>} Promise containing the server response
*/
uploadPhoto (file) {
let uri = `${baseUrl}/photos/`
const options = {
method: 'POST',
uri: uri,
headers: {
Authorization: `Bearer ${this.token}`,
'content-type': 'multipart/form-data'
},
resolveWithFullResponse: false,
formData: {
file: {
value: fs.createReadStream(file),
options: {
filename: path.parse(file).base,
contentType: 'image/jpeg'
}
}
}
}
return request(options)
}
/**
* Get the current human-readable status of a space created from a template
* @param {string} spaceId
* @returns {string} the current status
*/
getStatus(spaceId) {
return new Promise((resolve, reject) => {
const query = `query getSpace {
space(id: "${spaceId}") {
statusValueId
templateInfo {
spaceStatus {
defaultValue
acceptableValues {
id
displayName
}
}
}
}
}
`;
this.sendGraphql(query)
.then(result => {
const acceptableValue = result.space.templateInfo.spaceStatus.acceptableValues.find(function(value) {
return value.id === result.space.statusValueId;
});
resolve(acceptableValue.displayName);
})
.catch(err => {
reject(err);
});
});
}
/**
* Set the status of a space created from a template
* @param {string} spaceId The space Id
* @param {string} newStatus The human-readable status to set
*/
setStatus(spaceId, newStatus) {
return new Promise( (resolve, reject) => {
// first get the acceptable status values
const query = `query getSpace {
space(id: "${spaceId}") {
templateInfo {
spaceStatus {
acceptableValues {
id
displayName
}
}
}
}
}`;
this.sendGraphql(query)
.then(results => {
// now find the one which matches our new status
var statusValue = results.space.templateInfo.spaceStatus.acceptableValues.find(function(value) {
return value.displayName === newStatus;
});
if (statusValue) {
// set that status value Id into the mutation
const updateStatusMutation = `mutation {
updateSpace(input: {
id: "${spaceId}",
statusValue: {
statusValueId: "${statusValue.id}"
}
}
) {
memberIdsChanged
}
}`;
// and execute
resolve(this.sendGraphql(updateStatusMutation));
} else {
reject(`The value [${newStatus}] is not a valid status to set.`);
}
})
.catch(err => {
reject(err);
});
});
}
/**
* Return an array of the property display names and human-readable values.
* Each item in the array has a `propertyName` with the human-readable name of the property,
* and a `propertyValue` with the human-readable value, converted from the value's Id.
* This returns a promise for consistency with the other calls.
* @param {string} spaceId
* @returns {Promise<Object>} Promise containing an array of the properties.
*/
getProperties(spaceId) {
return new Promise((resolve, reject) => {
// this graphql will get the property definitions and their current values
const query = `query getSpace {
space(id: "${spaceId}") {
propertyValueIds {
propertyId
propertyValueId
}
templateInfo {
properties {
items {
id
displayName
type
... on SpaceListProperty {
acceptableValues {
id
displayName
}
}
}
}
}
}
}
`;
this.sendGraphql(query)
.then(result => {
const properties = []; // to hold the result
// iterate through the property definitions in the template info
for (let i = 0, itemsLength = result.space.templateInfo.properties.items.length; i < itemsLength; i++) {
// for each property definition, get the current value from the propertyValueIds array
const property = result.space.propertyValueIds.find(function(oneProperty) {
return oneProperty.propertyId === result.space.templateInfo.properties.items[i].id;
});
let propertyValue; // to hold the value
if (result.space.templateInfo.properties.items[i].type === 'LIST') {
// if it's a list type, get the human-readable value
const acceptableValue = result.space.templateInfo.properties.items[i].acceptableValues.find(function(value) {
return value.id === property.propertyValueId;
});
propertyValue = acceptableValue.displayName;
} else {
// if it's not a list type, the value is whatever is in the propertyValueId
propertyValue = property.propertyValueId;
}
properties.push({
propertyName: result.space.templateInfo.properties.items[i].displayName,
propertyValue: propertyValue
});
}
resolve(properties);
})
.catch(err => {
reject(err);
})
});
}
/**
* Set a property of a space created from a template.
* @param {*} spaceId the Id of the space.
* @param {*} propertyName The name of the property to set.
* @param {*} propertyValue The value of the property to set. For a property of
* type TEXT, this function will set the property value to whatever is passed in.
* For a property of type BOOLEAN, this function will attempt to convert the primitive
* boolean 'true' to the string TRUE and the primitive boolean 'false' to the string FALSE.
* @returns {Promise<Object>} Promise containing the server response, or a reject message.
*/
setProperty(spaceId, propertyName, propertyValue) {
return new Promise((resolve, reject) => {
// get all the property definitions
let query = `query getSpace {
space(id: "${spaceId}") {
templateInfo {
properties {
items {
id
displayName
type
... on SpaceListProperty {
acceptableValues {
id
displayName
}
}
}
}
}
}
}`;
this.sendGraphql(query)
.then(result => {
// find the property we want
const propertyDef = result.space.templateInfo.properties.items.find(function(item) {
return item.displayName === propertyName
});
if (typeof propertyDef === 'undefined') {
reject(`Property [${propertyName}] not defined in this space.`);
return;
}
// if BOOLEAN, check for a valid property and replace it with its string equivalent
if (propertyDef.type === 'BOOLEAN') {
if (typeof propertyValue === 'boolean') {
propertyValue = propertyValue === true ? 'TRUE' : 'FALSE';
} else {
reject(`Property value [${propertyValue}] invalid for property of type BOOLEAN`);
return;
}
// if LIST, find the matching acceptableValue and use that
} else if (propertyDef.type === 'LIST') {
// find the acceptableValue which matches our propertyValue
const acceptableValue = propertyDef.acceptableValues.find( function(value) {
return value.displayName === propertyValue;
});
if (acceptableValue) {
propertyValue = acceptableValue.id;
} else {
reject(`Acceptable Value [${propertyValue}] not found for property [${propertyName}]`);
return;
}
}
// if we got here, the inputs passed our checks and were converted if necessary.
// Run the Graphql.
const mutation = `mutation {
updateSpace(input: {
id: "${spaceId}",
propertyValues: [
{
propertyId: "${propertyDef.id}",
propertyValueId: "${propertyValue}"
}
]
}) {
memberIdsChanged
}
}`;
resolve(this.sendGraphql(mutation));
})
.catch(err => {
reject(err);
});
});
}
}
/**
* Sets the debug level. If 'debug' is used, request/response debug will be set.
* @param {string} level Level for debug e.g. error, info, warn, verbose, debug
*/
module.exports.level = level => {
logger.level = level
}
/**
* A user interface helper for sendTargetedMessage().
*/
module.exports.UI = ui