-
Notifications
You must be signed in to change notification settings - Fork 0
/
details.ts
223 lines (159 loc) · 6.47 KB
/
details.ts
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
import Command, { Flags, Args } from '../../base'
import Table from 'cli-table3'
import { clOutput, clColor, clUtil } from '@commercelayer/cli-core'
import axios from 'axios'
import { gunzipSync } from 'node:zlib'
import { dirname } from 'node:path'
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
import type { Import } from '@commercelayer/sdk'
export default class ImportsDetails extends Command {
static description = 'show the details of an existing import'
static aliases = ['imp:details']
static examples = [
'$ commercelayer imports:details <import-id>',
'$ cl imp:details <import-id> -i',
'$ cl imp:details <import-id> -i -l',
]
static flags = {
inputs: Flags.boolean({
char: 'i',
description: 'show input items associated with the import',
}),
logs: Flags.boolean({
char: 'l',
description: 'show warning and error logs related to the import process',
}),
'save-inputs': Flags.string({
char: 'S',
description: 'save import inputs to local file',
dependsOn: ['inputs'],
})
}
static args = {
id: Args.string({ name: 'id', description: 'unique id of the import', required: true, hidden: false })
}
async run(): Promise<any> {
const { args, flags } = await this.parse(ImportsDetails)
const id = args.id
const cl = this.commercelayerInit(flags)
try {
const imp = await cl.imports.retrieve(id)
const table = new Table({
// head: ['ID', 'Topic', 'Circuit state', 'Failures'],
colWidths: [23, 67],
colAligns: ['right', 'left'],
wordWrap: true,
})
const exclude = new Set(['type', 'reference', 'reference_origin', 'metadata', 'inputs', 'warnings_log', 'errors_log'])
// let index = 0
table.push(...Object.entries(imp)
.filter(([k]) => !exclude.has(k))
.map(([k, v]) => {
return [
{ content: clColor.table.key.blueBright(k), hAlign: 'right', vAlign: 'center' },
this.formatValue(k, v as string),
]
}))
if (imp.metadata?.group_id) table.splice(1, 0, [clColor.table.key.cyanBright('group_id'), clColor.api.id(String(imp.metadata.group_id))])
this.log()
this.log(table.toString())
this.log()
if (flags.inputs) {
const inputs = (!imp.inputs && imp.attachment_url) ? await this.getInputs(imp) : imp.inputs
this.showInputs(inputs)
if (flags['save-inputs'] && inputs) this.saveInputs(flags, inputs)
}
if (flags.logs) this.showLogs(imp.warnings_log, imp.errors_log)
return imp
} catch (error: any) {
this.handleError(error as Error, flags, id)
}
}
private async getInputs(imp: Import): Promise<any[]> {
if (!imp.attachment_url) return []
const inputs = await axios.get(imp.attachment_url, { responseType: 'arraybuffer' })
if (!inputs) return []
const unzipped = gunzipSync(inputs.data as ArrayBuffer).toString()
return (imp.format === 'csv') ? unzipped.split('\n') : JSON.parse(unzipped)
}
private saveInputs(flags: any, inputs: any[]): void {
let filePath: string = flags['save-inputs']
if (!filePath) this.warn('Undefined output save path')
filePath = clUtil.specialFolder(filePath)
const fileDir = dirname(filePath)
if (flags['save-path'] && !existsSync(fileDir)) mkdirSync(fileDir, { recursive: true })
writeFileSync(filePath, clOutput.printJSON(inputs, { tabSize: 4 }), { encoding: 'utf-8' })
}
private showInputs(inputs?: object[]): void {
const imp = inputs || []
this.log()
this.log(clColor.cyanBright(`${clColor.bold('INPUTS')}\t[ ${imp.length} record${imp.length === 1 ? '' : 's'} ]`))
if (imp.length > 0) {
const table = new Table({ colWidths: [90], wordWrap: true })
table.push(...imp.map(i => [clOutput.printObject(i, { width: 86 })]))
this.log(table.toString())
}
this.log()
}
private showLogs(warningLog?: Record<string, any> | null, errorLog?: Record<string, any> | null): void {
const tableOptions: Table.TableConstructorOptions = {
head: ['Code', 'Message'],
colWidths: [15, 75],
// colAligns: ['center', 'left'],
wordWrap: true,
style: {
head: ['brightCyan'],
compact: false,
},
}
// Warnings
const warnings = warningLog ? Object.keys(warningLog).length : 0
this.log()
this.log(clColor.msg.warning.yellowBright(`${clColor.bold('WARNING LOG')}\t[ ${warnings} warning${warnings === 1 ? '' : 's'} ]`))
if (warnings > 0) {
const table = new Table(tableOptions)
table.push(...Object.entries(warningLog || {})
.map(([k, v]) => [{ content: ((k && (k !== 'unknown')) ? k : ''), vAlign: 'center' }, clOutput.printObject(v) as any]))
this.log(table.toString())
}
this.log()
// Errors
const errors = errorLog ? Object.keys(errorLog).length : 0
this.log()
this.log(clColor.msg.error(`${clColor.bold('ERROR LOG')}\t[ ${errors} error${errors === 1 ? '' : 's'} ]`))
if (errors > 0) {
const table = new Table(tableOptions)
table.push(...(Object.entries(errorLog || {}))
.map(([k, v]) => [{ content: ((k && (k !== 'unknown')) ? k : ''), vAlign: 'center' }, clOutput.printObject(v) as any]))
this.log(table.toString())
}
this.log()
}
private formatValue(field: string, value: string): any {
if (field.endsWith('_date') || field.endsWith('_at')) return clOutput.localeDate(value)
switch (field) {
case 'id': return clColor.api.id(value)
case 'resource_type': return clColor.magentaBright(value)
case 'topic': return clColor.magenta(value)
case 'status': return this.importStatus(value)
case 'warnings_count': return clColor.msg.warning(value)
case 'errors_count': return clColor.msg.error(value)
case 'destroyed_count': return clColor.cyanBright(value)
case 'processed_count': return clColor.msg.success(value)
case 'metadata': {
const t = new Table({ style: { compact: false } })
t.push(...Object.entries(value).map(([k, v]) => {
return [
{ content: clColor.cyan.italic(k), hAlign: 'left', vAlign: 'center' },
{ content: clColor.cli.value((typeof v === 'object') ? JSON.stringify(v) : v) } as any,
]
}))
return t.toString()
}
default: {
if ((typeof value === 'object') && (value !== null)) return JSON.stringify(value, undefined, 4)
return String(value)
}
}
}
}