This repository has been archived by the owner on Oct 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
request.js
101 lines (90 loc) · 2.62 KB
/
request.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
const Command = require('../base')
const {flags} = require('@oclif/command')
const globalFlags = require('../helpers/global-flags')
const jsonHelper = require('../helpers/json')
const requestHelper = require('../helpers/request')
const fs = require('fs')
const ora = require('ora')
const chalk = require('chalk')
/**
* Runs an arbitrary HTTP request against the Chec API
*/
class RequestCommand extends Command {
requiresAuth() {
return true
}
async run() {
const spinner = ora({
text: 'Processing...',
stream: process.stdout,
}).start()
const {args, flags: {domain, sandbox, file}} = this.parse(RequestCommand)
let parsedPayload
try {
if (args.payload) {
parsedPayload = JSON.parse(args.payload)
} else if (file) {
parsedPayload = JSON.parse(fs.readFileSync(file))
}
} catch (error) {
spinner.fail('Failed to parse your input payload. Please provide valid JSON.')
if (file && !fs.existsSync(file)) {
this.error(`Input file ${chalk.yellow(file)} could not be opened`)
}
return
}
try {
const result = await requestHelper.request(args.method, args.resource, parsedPayload, {
domain,
sandbox,
})
spinner.stop()
this.log(jsonHelper.prettify(result.body))
} catch (error) {
spinner.fail('Request failed: ' + error.statusCode + ' ' + error.statusMessage)
this.error(jsonHelper.prettify(error.body))
}
}
}
RequestCommand.description = `Run abstract API request
Runs an arbitrary API request given the HTTP method, endpoint, and input payload.
Data should be provided as a JSON object. You may also use \`--sandbox\` to use
sandbox API keys.
`
RequestCommand.args = [
{
name: 'method',
required: true,
description: 'HTTP method',
options: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
},
{
name: 'resource',
required: true,
description: 'API resource (e.g. /v1/products)',
},
{
name: 'payload',
required: false,
description: 'Request payload (JSON encoded)',
},
]
RequestCommand.flags = {
...globalFlags,
sandbox: flags.boolean({
description: 'Use sandbox API keys',
default: false,
}),
file: flags.string({
description: 'Optional: path to JSON encoded file containing request payload',
default: null,
}),
}
RequestCommand.examples = [
'$ chec request GET /v1/products',
'$ chec request GET /v1/orders',
'$ chec request GET /v1/products \'{"limit":1}\'',
'$ chec request GET /v1/products \'{"limit":1}\' --sandbox',
'$ chec request POST /v1/assets --file=my-asset-payload.json',
]
module.exports = RequestCommand