Skip to content

1. Commands

Mengting Yan edited this page Apr 20, 2020 · 3 revisions

You can think of Kui commands as Express Routes. As with Express, you need to tell Kui two things. First, you need to implement a command handler. Second, you need to map that handler to a route. In the case of Kui, this entails assigning a command-line strings to a particular command handler. More so, just as express endpoints return a data model (to be rendered subsequently into some view in the browser), Kui commands also return a data model as opposed to a view.

Command Handler and Response

If your command handler returns one the following data types, it will be rendered in the Kui Terminal view: string, boolean, and Table. More complex data types can be presented in custom views, see Commands that Interact with Views. For example, Kui includes a Sidecar view component, some examples of which are shown on the top page. This page focuses on command handlers that are intended to be presented in the Terminal.

Option 1: Return a string to terminal

export const printString = () => 'Hello!'

Option 2: Return a boolean to terminal

export const printOK = () => true

Option 3: Return a Table to terminal

To render a table in terminal, your command handler will return a Table model. Kui then visualizes the table for you using a built-in view. This built-in view uses the Carbon Components library. Here's an example of returning a 2x2 Table:

import { Table } from '@kui-shell/core'

export const printTable = (): Table => ({
  header: { name: 'Column1', attributes: [{ value: 'Column2' }]},
  body: [
    { name: 'Row1Column1', attributes: [{ value: 'Row1Column2' }]},
    { name: 'Row2Column1', attributes: [{ value: 'Row2Column2' }]}
  ]
})

Command Routing and Registration

Kui command routing and registration is similar to Express routing. You register your command handler by identifying the name of the command that will trigger the handler.

For example, if you wish Kui to respond to the command-line > hello world using the printString() command handler from above, you would register the command handler as follows:

import { Registrar } from '@kui-shell/core'
import { printString } from './view/string'

export default async (kui: Registrar) => {
  kui.listen('/hello/world', printString)
}

If you place this source code in a file named plugin.ts, Kui will automatically scan your source code to locate it, and then automatically process its registrations.

Next Steps