@adobe/aio-cli-plugin-api-mesh 1.0.0-beta → 1.0.1-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/helpers.js CHANGED
@@ -9,88 +9,189 @@ OF ANY KIND, either express or implied. See the License for the specific languag
9
9
  governing permissions and limitations under the License.
10
10
  */
11
11
 
12
- const Config = require('@adobe/aio-lib-core-config')
13
- const { getToken, context } = require('@adobe/aio-lib-ims')
14
- const { CLI } = require('@adobe/aio-lib-ims/src/context')
15
- const fs = require('fs')
16
- const libConsoleCLI = require('@adobe/aio-cli-lib-console')
17
- const { SchemaServiceClient } = require('./classes/SchemaServiceClient')
18
- const { getCliEnv } = require('@adobe/aio-lib-env')
19
- const aioConsoleLogger = require('@adobe/aio-lib-core-logging')('@adobe/aio-cli-plugin-commerce-admin', { provider: 'debug' })
20
- const CONSOLE_CONFIG_KEYS = {
21
- CONSOLE: 'console',
22
- ORG: 'org'
23
- }
12
+ const Config = require('@adobe/aio-lib-core-config');
13
+ const { getToken, context } = require('@adobe/aio-lib-ims');
14
+ const { CLI } = require('@adobe/aio-lib-ims/src/context');
15
+ const fs = require('fs');
16
+ const libConsoleCLI = require('@adobe/aio-cli-lib-console');
17
+ const { SchemaServiceClient } = require('./classes/SchemaServiceClient');
18
+ const { getCliEnv } = require('@adobe/aio-lib-env');
19
+ const logger = require('../src/classes/logger');
20
+ const { UUID } = require('./classes/UUID');
21
+ const aioConsoleLogger = require('@adobe/aio-lib-core-logging')(
22
+ '@adobe/aio-cli-plugin-api-mesh',
23
+ { provider: 'debug' },
24
+ );
25
+
24
26
  const CONSOLE_API_KEYS = {
25
- prod: 'aio-cli-console-auth',
26
- stage: 'aio-cli-console-auth-stage'
27
- }
27
+ prod: 'aio-cli-console-auth',
28
+ stage: 'aio-cli-console-auth-stage',
29
+ };
28
30
 
29
31
  /**
30
32
  * @returns {any} Returns a config object or null
31
33
  */
32
- async function getCommerceAdminConfig () {
33
- const configFile = Config.get('aio-cli-plugin-commerce-admin')
34
- try {
35
- const data = JSON.parse((fs.readFileSync(configFile,
36
- { encoding: 'utf8', flag: 'r' })))
37
- return {
38
- baseUrl: data.baseUrl || 'https://commerce.adobe.io',
39
- accessToken: (await getLibConsoleCLI()).accessToken,
40
- apiKey: data.apiKey
41
- }
42
- } catch (error) {
43
- return null
44
- }
34
+ async function getDevConsoleConfig() {
35
+ const configFile = Config.get('api-mesh.configPath');
36
+
37
+ if (!configFile) {
38
+ return {
39
+ baseUrl: 'https://developers.adobe.io/console',
40
+ accessToken: (await getLibConsoleCLI()).accessToken,
41
+ apiKey: 'adobe-graph-prod',
42
+ };
43
+ } else {
44
+ try {
45
+ if (!fs.existsSync(configFile)) {
46
+ throw new Error(
47
+ `Config file does not exist. Please run the command: aio config:set api-mesh.configPath <path_to_json_file> with a valid file.`,
48
+ );
49
+ }
50
+
51
+ const data = JSON.parse(fs.readFileSync(configFile, { encoding: 'utf8', flag: 'r' }));
52
+
53
+ if (!data.baseUrl || !data.apiKey) {
54
+ throw new Error(
55
+ 'Invalid config file. Please validate the file contents and try again. Config file must contain baseUrl and apiKey.',
56
+ );
57
+ }
58
+
59
+ const baseUrl = data.baseUrl.endsWith('/')
60
+ ? data.baseUrl.slice(0, data.baseUrl.length - 1)
61
+ : data.baseUrl;
62
+
63
+ return {
64
+ baseUrl: baseUrl,
65
+ accessToken: (await getLibConsoleCLI()).accessToken,
66
+ apiKey: data.apiKey,
67
+ };
68
+ } catch (error) {
69
+ logger.error(
70
+ 'Please run the command: aio config:set api-mesh.configPath <path_to_json_file> with a valid config file.',
71
+ );
72
+
73
+ throw new Error(error);
74
+ }
75
+ }
45
76
  }
46
77
 
47
78
  /**
48
79
  * @returns {string} Returns organizations the user belongs to
49
80
  */
50
- async function getAuthorizedOrganizations () {
51
- const { consoleCLI } = await getLibConsoleCLI()
52
- aioConsoleLogger.debug('Get the selected organization')
53
- const key = CONSOLE_CONFIG_KEYS.ORG
54
- this.configOrgCode = Config.get(`${CONSOLE_CONFIG_KEYS.CONSOLE}.${key}`)
55
- if (!this.configOrgCode) {
56
- const organizations = await consoleCLI.getOrganizations()
57
- const selectedOrg = await consoleCLI.promptForSelectOrganization(organizations)
58
- aioConsoleLogger.debug('Set the console config')
59
- Config.set(`${CONSOLE_CONFIG_KEYS.CONSOLE}.${key}`, { id: selectedOrg.id, code: selectedOrg.code, name: selectedOrg.name })
60
- this.imsOrgCode = selectedOrg.code
61
- return { imsOrgCode: this.imsOrgCode }
62
- } else {
63
- console.log(`Selecting your organization as: ${this.configOrgCode.name}`)
64
- return { imsOrgCode: this.configOrgCode.code }
65
- }
81
+ async function getAuthorizedOrganization() {
82
+ const { consoleCLI } = await getLibConsoleCLI();
83
+
84
+ aioConsoleLogger.debug('Get the selected organization');
85
+
86
+ const consoleConfigOrg = Config.get('console.org');
87
+
88
+ if (!consoleConfigOrg) {
89
+ const organizations = await consoleCLI.getOrganizations();
90
+ const selectedOrg = await consoleCLI.promptForSelectOrganization(organizations);
91
+
92
+ aioConsoleLogger.debug('Set the console config');
93
+
94
+ Config.set('console.org', {
95
+ id: selectedOrg.id,
96
+ code: selectedOrg.code,
97
+ name: selectedOrg.name,
98
+ });
99
+
100
+ return Object.assign({}, selectedOrg);
101
+ } else {
102
+ logger.info(`Selecting your organization as: ${consoleConfigOrg.name}`);
103
+
104
+ return Object.assign({}, consoleConfigOrg);
105
+ }
106
+ }
107
+
108
+ async function getProject(imsOrgId, imsOrgTitle) {
109
+ logger.info(`Initializing project selection for ${imsOrgId}`);
110
+
111
+ const { consoleCLI } = await getLibConsoleCLI();
112
+
113
+ const projects = await consoleCLI.getProjects(imsOrgId);
114
+ if (projects.length !== 0) {
115
+ const selectedProject = await consoleCLI.promptForSelectProject(projects);
116
+
117
+ return selectedProject;
118
+ } else {
119
+ aioConsoleLogger.error(`No projects found for the selected organization: ${imsOrgTitle}`);
120
+ }
66
121
  }
122
+
123
+ async function getWorkspace(orgId, projectId, imsOrgTitle, projectTitle) {
124
+ logger.info(`Initializing workspace selection for ${orgId} / ${projectId}`);
125
+
126
+ const { consoleCLI } = await getLibConsoleCLI();
127
+
128
+ const workspaces = await consoleCLI.getWorkspaces(orgId, projectId);
129
+ if (workspaces.length !== 0) {
130
+ const selectedWorkspace = await consoleCLI.promptForSelectWorkspace(workspaces);
131
+
132
+ return selectedWorkspace;
133
+ } else {
134
+ aioConsoleLogger.error(
135
+ `No workspaces found for the selected organization: ${imsOrgTitle} and project: ${projectTitle}`,
136
+ );
137
+ }
138
+ }
139
+
67
140
  /**
68
141
  * @private
69
142
  */
70
- async function getLibConsoleCLI () {
71
- await context.setCli({ 'cli.bare-output': true }, false)
72
- const clientEnv = getCliEnv()
73
- this.accessToken = await getToken(CLI)
74
- this.consoleCLI = await libConsoleCLI.init({ accessToken: this.accessToken, apiKey: CONSOLE_API_KEYS[clientEnv], env: clientEnv })
75
- return { consoleCLI: this.consoleCLI, accessToken: this.accessToken }
143
+ async function getLibConsoleCLI() {
144
+ await context.setCli({ 'cli.bare-output': true }, false);
145
+
146
+ const clientEnv = getCliEnv();
147
+
148
+ const accessToken = await getToken(CLI);
149
+
150
+ const consoleCLI = await libConsoleCLI.init({
151
+ accessToken: accessToken,
152
+ apiKey: CONSOLE_API_KEYS[clientEnv],
153
+ env: clientEnv,
154
+ });
155
+
156
+ return { consoleCLI: consoleCLI, accessToken: accessToken };
76
157
  }
77
158
 
78
159
  /**
79
160
  * @returns {any} Returns an object with properties ready for consumption
80
161
  */
81
- async function initSdk () {
82
- const { imsOrgCode } = await getAuthorizedOrganizations()
83
- console.log('Initialized user login and the selected organization')
84
- const { baseUrl, accessToken, apiKey } = await getCommerceAdminConfig()
85
- const schemaServiceClient = new SchemaServiceClient()
86
- schemaServiceClient.init(baseUrl, accessToken, apiKey)
87
- return {
88
- schemaServiceClient: schemaServiceClient,
89
- imsOrgCode: imsOrgCode
90
- }
162
+ async function initSdk() {
163
+ const org = await getAuthorizedOrganization();
164
+ const project = await getProject(org.id, org.name);
165
+ const workspace = await getWorkspace(org.id, project.id, org.name, project.title);
166
+
167
+ aioConsoleLogger.log(
168
+ `Initializing SDK for org: ${org.name}, project: ${project.title} and workspace: ${workspace.title}`,
169
+ );
170
+
171
+ logger.info('Initialized user login and the selected organization');
172
+
173
+ const { baseUrl, accessToken, apiKey } = await getDevConsoleConfig();
174
+
175
+ const schemaServiceClient = new SchemaServiceClient();
176
+ schemaServiceClient.init(baseUrl, accessToken, apiKey);
177
+
178
+ return {
179
+ schemaServiceClient: schemaServiceClient,
180
+ imsOrgId: org.id,
181
+ projectId: project.id,
182
+ workspaceId: workspace.id,
183
+ };
91
184
  }
92
185
 
93
- module.exports = {
94
- getCommerceAdminConfig,
95
- initSdk
186
+ /**
187
+ * Generates a static global requestid for the lifecycle of this command request
188
+ */
189
+ async function initRequestId() {
190
+ global.requestId = UUID.newUuid().toString();
96
191
  }
192
+
193
+ module.exports = {
194
+ getDevConsoleConfig,
195
+ initSdk,
196
+ initRequestId,
197
+ };
package/src/utils.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Returns the string representation of the object's path.
3
+ * If the path evaluates to false, the default string is returned.
4
+ *
5
+ * @param {object} obj
6
+ * @param {array<string>} path
7
+ * @param {string} defaultString
8
+ *
9
+ * @returns {string}
10
+ */
11
+ function objToString(obj, path, defaultString = '') {
12
+ try {
13
+ // Cache the current object
14
+ let current = obj;
15
+
16
+ // For each item in the path, dig into the object
17
+ for (let i = 0; i < path.length; i++) {
18
+ // If the item isn't found, return the default (or null)
19
+ if (!current[path[i]]) return defaultString;
20
+
21
+ // Otherwise, update the current value
22
+ current = current[path[i]];
23
+ }
24
+
25
+ if (typeof current === 'string') {
26
+ return current;
27
+ } else if (typeof current === 'object') {
28
+ return JSON.stringify(current, null, 2);
29
+ } else {
30
+ return defaultString;
31
+ }
32
+ } catch (error) {
33
+ return defaultString;
34
+ }
35
+ }
36
+
37
+ module.exports = {
38
+ objToString,
39
+ };
@@ -1,42 +0,0 @@
1
- /*
2
- Copyright 2021 Adobe. All rights reserved.
3
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- you may not use this file except in compliance with the License. You may obtain a copy
5
- of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- Unless required by applicable law or agreed to in writing, software distributed under
7
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
- OF ANY KIND, either express or implied. See the License for the specific language
9
- governing permissions and limitations under the License.
10
- */
11
-
12
- const { Command } = require('@oclif/command')
13
- const { readFile } = require('fs/promises')
14
- const { initSdk } = require('../../../helpers')
15
-
16
- class CreateCommand extends Command {
17
- static args = [
18
- { name: 'file' }
19
- ]
20
-
21
- async run () {
22
- console.log('Start create tenant')
23
- const { args } = this.parse(CreateCommand)
24
- const { schemaServiceClient, imsOrgCode } = await initSdk()
25
- let data
26
- try {
27
- data = JSON.parse(await readFile(args.file, 'utf8'))
28
- } catch (error) {
29
- this.error('Unable to create a tenant with the given configuration')
30
- }
31
- data.imsOrgId = imsOrgCode
32
- const tenant = await schemaServiceClient.createTenant(data)
33
- tenant
34
- ? this.log(`Successfully created a tenant with the ID: ${data.tenantId} and imsOrgCode: ${data.imsOrgId}`)
35
- : this.error(`Unable to create a tenant with the ID ${data.tenantId}`)
36
- return tenant
37
- }
38
- }
39
-
40
- CreateCommand.description = 'Create a tenant with the given config.'
41
-
42
- module.exports = CreateCommand
@@ -1,33 +0,0 @@
1
- /*
2
- Copyright 2021 Adobe. All rights reserved.
3
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- you may not use this file except in compliance with the License. You may obtain a copy
5
- of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- Unless required by applicable law or agreed to in writing, software distributed under
7
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
- OF ANY KIND, either express or implied. See the License for the specific language
9
- governing permissions and limitations under the License.
10
- */
11
-
12
- const { Command } = require('@oclif/command')
13
- const { initSdk } = require('../../../helpers')
14
-
15
- class GetCommand extends Command {
16
- static args = [
17
- { name: 'tenantId' }
18
- ]
19
-
20
- async run () {
21
- const { args } = this.parse(GetCommand)
22
- const { schemaServiceClient, imsOrgCode } = await initSdk()
23
- const tenant = await schemaServiceClient.getTenant(args.tenantId, imsOrgCode)
24
- tenant
25
- ? this.log(JSON.stringify(tenant))
26
- : this.error(`Unable to retrieve the tenant config for ${args.tenantId}`)
27
- return tenant
28
- }
29
- }
30
-
31
- GetCommand.description = 'Get the config of a given tenant'
32
-
33
- module.exports = GetCommand
@@ -1,42 +0,0 @@
1
- /*
2
- Copyright 2021 Adobe. All rights reserved.
3
- This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- you may not use this file except in compliance with the License. You may obtain a copy
5
- of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- Unless required by applicable law or agreed to in writing, software distributed under
7
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
- OF ANY KIND, either express or implied. See the License for the specific language
9
- governing permissions and limitations under the License.
10
- */
11
-
12
- const { Command } = require('@oclif/command')
13
- const { readFile } = require('fs/promises')
14
- const { initSdk } = require('../../../helpers')
15
-
16
- class UpdateCommand extends Command {
17
- static args = [
18
- { name: 'tenantId' },
19
- { name: 'file' }
20
- ]
21
-
22
- async run () {
23
- const { args } = this.parse(UpdateCommand)
24
- const { schemaServiceClient, imsOrgCode } = await initSdk()
25
- let data
26
- try {
27
- data = JSON.parse(await readFile(args.file, 'utf8'))
28
- } catch (error) {
29
- this.error('Unable to update the tenant with the given configuration')
30
- }
31
- data.imsOrgId = imsOrgCode
32
- const tenant = await schemaServiceClient.updateTenant(args.tenantId, data)
33
- tenant
34
- ? this.log(`Successfully updated the tenant with the id: ${data.tenantId}`)
35
- : this.log(`Unable to update the tenant with the id: ${data.tenantId}`)
36
- return tenant
37
- }
38
- }
39
-
40
- UpdateCommand.description = 'Update a tenant with the given config.'
41
-
42
- module.exports = UpdateCommand