1 | const Command = require('../utils/command')
|
2 | const AsciiTable = require('ascii-table')
|
3 | const chalk = require('chalk')
|
4 | const oclif = require('@oclif/command')
|
5 | const { methods } = require('netlify')
|
6 | const { isEmptyCommand } = require('../utils/check-command-inputs')
|
7 |
|
8 | class APICommand extends Command {
|
9 | async run() {
|
10 | const { api } = this.netlify
|
11 | const { args, flags } = this.parse(APICommand)
|
12 |
|
13 | const { apiMethod } = args
|
14 |
|
15 | await this.config.runHook('analytics', {
|
16 | eventName: 'command',
|
17 | payload: {
|
18 | command: 'api'
|
19 | }
|
20 | })
|
21 |
|
22 | if (isEmptyCommand(flags, args) || flags.list) {
|
23 | const table = new AsciiTable(`Netlify API Methods`)
|
24 | table.setHeading('API Method', 'Docs Link')
|
25 | methods.forEach(method => {
|
26 | const { operationId } = method
|
27 | table.addRow(operationId, `https://open-api.netlify.com/#/operation/${operationId}`)
|
28 | })
|
29 | this.log(table.toString())
|
30 | this.log()
|
31 | this.log('Above is a list of available API methods')
|
32 | this.log(`To run a method use "${chalk.cyanBright('netlify api methodName')}"`)
|
33 | this.exit()
|
34 | }
|
35 |
|
36 | if (!apiMethod) {
|
37 | this.error(`You must provide an API method. Run "netlify api --list" to see available methods`)
|
38 | }
|
39 |
|
40 | if (!api[apiMethod] || typeof api[apiMethod] !== 'function') {
|
41 | this.error(`"${apiMethod}"" is not a valid api method. Run "netlify api --list" to see available methods`)
|
42 | }
|
43 |
|
44 | if (flags.data) {
|
45 | const payload = typeof flags.data === 'string' ? JSON.parse(flags.data) : flags.data
|
46 | try {
|
47 | const apiResponse = await api[apiMethod](payload)
|
48 | this.log(JSON.stringify(apiResponse, null, 2))
|
49 | } catch (e) {
|
50 | this.error(e)
|
51 | }
|
52 | }
|
53 | }
|
54 | }
|
55 |
|
56 | APICommand.description = `Run any Netlify API method
|
57 |
|
58 | For more information on available methods checkout https://open-api.netlify.com/ or run "netlify api --list"
|
59 | `
|
60 |
|
61 | APICommand.args = [
|
62 | {
|
63 | name: 'apiMethod',
|
64 | description: 'Open API method to run'
|
65 | }
|
66 | ]
|
67 |
|
68 | APICommand.examples = ['netlify api --list', 'netlify api getSite --data \'{ "site_id": "123456"}\'']
|
69 |
|
70 | APICommand.flags = {
|
71 | data: oclif.flags.string({
|
72 | char: 'd',
|
73 | description: 'Data to use'
|
74 | }),
|
75 | list: oclif.flags.boolean({
|
76 | description: 'List out available API methods'
|
77 | })
|
78 | }
|
79 |
|
80 | APICommand.strict = false
|
81 |
|
82 | module.exports = APICommand
|