11const OpenAPI = require ( '@tuyapi/openapi' ) ;
22const inquirer = require ( 'inquirer' ) ;
33const colors = require ( 'colors' ) ;
4+ const any = require ( 'promise.any' ) ;
5+
6+ const REGIONS = [ 'eu' , 'us' , 'cn' ] ;
47
58const list = async conf => {
69 let questions = [
@@ -18,16 +21,6 @@ const list = async conf => {
1821 {
1922 name : 'apiSecret' ,
2023 message : 'The API secret from tuya.com'
21- } ,
22- {
23- name : 'region' ,
24- message : 'Select the region closest to you:' ,
25- type : 'list' ,
26- choices : [
27- { name : 'Americas' , value : 'us' } ,
28- { name : 'Europe' , value : 'eu' } ,
29- { name : 'Asia' , value : 'cn' }
30- ]
3124 }
3225 ] ;
3326
@@ -59,21 +52,31 @@ const list = async conf => {
5952 if ( useExistingKeys ) {
6053 answers . apiKey = savedAPIKey ;
6154 answers . apiSecret = savedAPISecret ;
62- answers . region = savedAPIRegion ;
6355 }
6456
65- // Create API instance
66- const api = new OpenAPI ( { key : answers . apiKey , secret : answers . apiSecret , region : answers . region } ) ;
67-
68- await api . getToken ( ) ;
69-
7057 // Get seed device
7158 let userId = null ;
59+ let foundAPIRegion = savedAPIRegion ;
7260
7361 try {
74- const device = await api . getDevice ( answers . deviceId ) ;
75-
76- userId = device . uid ;
62+ if ( savedAPIRegion && useExistingKeys ) {
63+ const api = new OpenAPI ( { key : answers . apiKey , secret : answers . apiSecret , region : savedAPIRegion } ) ;
64+ await api . getToken ( ) ;
65+ const device = await api . getDevice ( answers . deviceId ) ;
66+
67+ userId = device . uid ;
68+ } else {
69+ const { device, region} = await any ( REGIONS . map ( async region => {
70+ const api = new OpenAPI ( { key : answers . apiKey , secret : answers . apiSecret , region} ) ;
71+ await api . getToken ( ) ;
72+ const device = await api . getDevice ( answers . deviceId ) ;
73+
74+ return { device, region} ;
75+ } ) ) ;
76+
77+ userId = device . uid ;
78+ foundAPIRegion = region ;
79+ }
7780 } catch {
7881 console . error ( colors . red ( 'There was an issue fetching that device. Make sure your account is linked and the ID is correct.' ) ) ;
7982
@@ -82,6 +85,8 @@ const list = async conf => {
8285 }
8386
8487 // Get user devices
88+ const api = new OpenAPI ( { key : answers . apiKey , secret : answers . apiSecret , region : foundAPIRegion } ) ;
89+ await api . getToken ( ) ;
8590 const devices = await api . getDevicesByUser ( userId ) ;
8691
8792 // Output devices
@@ -90,7 +95,7 @@ const list = async conf => {
9095 // Save API key and secret
9196 conf . set ( 'apiKey' , answers . apiKey ) ;
9297 conf . set ( 'apiSecret' , answers . apiSecret ) ;
93- conf . set ( 'apiRegion' , answers . region ) ;
98+ conf . set ( 'apiRegion' , foundAPIRegion ) ;
9499} ;
95100
96101module . exports = list ;
0 commit comments