Skip to content

Commit

Permalink
feat(REACH-717): add bin to run the client from command line (#99)
Browse files Browse the repository at this point in the history
Add command line client that can be executed with `yarn typeform-api`.
  • Loading branch information
mathio authored Oct 5, 2023
1 parent a74622a commit c48541f
Show file tree
Hide file tree
Showing 5 changed files with 146 additions and 3 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# output folder
dist/
rollup.config.js
42 changes: 41 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ npm install @typeform/api-client --save

## Usage

### Initialize
### In your project

1. Import client library

Expand Down Expand Up @@ -72,6 +72,46 @@ typeformAPI.forms.list().then((response) => {
})
```

**Note:** You can also execute the client binary directly via command line in your project:

```shell
yarn typeform-api <method> [params]
```

See [next section](#via-command-line) for more details.

### Via command line

1. Clone this repo on your machine

2. Install all dependencies:

```shell
yarn install
```

3. Set your personal token as `TF_TOKEN` env variable

```shell
export TF_TOKEN=tfp_XXXXXXXXXX
```

4. Run the client:

```shell
yarn typeform-api <method> [params]
```

See [reference](#reference) for all available method names and their params.

Example usage:

```shell
yarn typeform-api forms.list
yarn typeform-api forms.get '{uid:"abcd1234"}'
yarn typeform-api themes.list '{pageSize:3}'
```

## Reference

### `createClient({token})`
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@
"semantic-release": "semantic-release",
"server": "node ./tests/integration/mockServer.js",
"server:dev": "nodemon ./tests/integration/mockServer.js",
"publish:github": "npm config set '//npm.pkg.github.com/:_authToken' $GH_TOKEN && npm publish --registry https://npm.pkg.github.com"
"publish:github": "npm config set '//npm.pkg.github.com/:_authToken' $GH_TOKEN && npm publish --registry https://npm.pkg.github.com",
"typeform-api": "node ./dist/bin"
},
"bin": {
"typeform-api": "dist/bin"
},
"main": "dist/index.cjs.js",
"browser": "dist/typeform-api.js",
Expand Down
39 changes: 38 additions & 1 deletion rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,43 @@ const config = [
terser(),
],
},
{
input: 'src/bin.ts',
output: [
{
file: pkg.bin['typeform-api'],
format: 'cjs',
exports: 'named',
banner: '#!/usr/bin/env node',
},
],
onwarn(warning, warn) {
// supress warning on usa of eval()
// eval() in ./src/bin.ts executes code supplied by user on their own machine, which is safe
if (warning.code === 'EVAL') {
return
}
warn(warning)
},
plugins: [
resolveModule(),
commonjs({
include: ['node_modules/**'],
}),
...plugins,
],
external: [
'http',
'https',
'url',
'zlib',
'assert',
'stream',
'tty',
'util',
'os',
],
},
]

export default config
export default config
61 changes: 61 additions & 0 deletions src/bin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { inspect } from 'util'

import { createClient } from './index'

const print = (message: string) => {
// eslint-disable-next-line no-console
console.log(message)
}

const token = process.env.TF_TOKEN

if (!token) {
throw new Error('Add your personal token as TF_TOKEN env variable')
}

const typeformAPI = createClient({ token })

const [, , ...args] = process.argv
const [methodName, methodParams] = args

if (!methodName || methodName === '-h' || methodName === '--help') {
print('usage: typeform-api <method> [params]')
print('examples: yarn api forms.list')
print(' yarn api forms.get \'{uid:"abc12345"}\'')
print(" yarn api themes.list '{pageSize:3}'")
process.exit(0)
}

const [property, method] = methodName.split('.')

// @ts-ignore
if (!typeformAPI[property]?.[method]) {
throw new Error(`Method ${methodName} does not exist`)
}

let parsedParams = undefined

if (methodParams) {
try {
// this eval executes code supplied by user on their own machine, this is safe
// eslint-disable-next-line no-eval
eval(`parsedParams = ${methodParams}`)
} catch (err) {
throw new Error(`Invalid params: ${methodParams}`)
}

if (typeof parsedParams !== 'object') {
throw new Error(`Invalid params: ${methodParams}`)
}
}

print(`API: ${methodName}():`)

// @ts-ignore
typeformAPI[property][method](parsedParams)
.then((result: Object) => {
print(inspect(result, { showHidden: false, depth: null, colors: true }))
})
.catch((err: Error) => {
print(`Error: ${err.message}`)
})

0 comments on commit c48541f

Please sign in to comment.