|
| 1 | +import { inspect } from 'util' |
| 2 | + |
| 3 | +import { createClient } from './index' |
| 4 | + |
| 5 | +const print = (message: string) => { |
| 6 | + // eslint-disable-next-line no-console |
| 7 | + console.log(message) |
| 8 | +} |
| 9 | + |
| 10 | +const token = process.env.TF_TOKEN |
| 11 | + |
| 12 | +if (!token) { |
| 13 | + throw new Error('Add your personal token as TF_TOKEN env variable') |
| 14 | +} |
| 15 | + |
| 16 | +const typeformAPI = createClient({ token }) |
| 17 | + |
| 18 | +const [, , ...args] = process.argv |
| 19 | +const [methodName, methodParams] = args |
| 20 | + |
| 21 | +if (!methodName || methodName === '-h' || methodName === '--help') { |
| 22 | + print('usage: typeform-api <method> [params]') |
| 23 | + print('examples: yarn api forms.list') |
| 24 | + print(' yarn api forms.get \'{uid:"abc12345"}\'') |
| 25 | + print(" yarn api themes.list '{pageSize:3}'") |
| 26 | + process.exit(0) |
| 27 | +} |
| 28 | + |
| 29 | +const [property, method] = methodName.split('.') |
| 30 | + |
| 31 | +// @ts-ignore |
| 32 | +if (!typeformAPI[property]?.[method]) { |
| 33 | + throw new Error(`Method ${methodName} does not exist`) |
| 34 | +} |
| 35 | + |
| 36 | +let parsedParams = undefined |
| 37 | + |
| 38 | +if (methodParams) { |
| 39 | + try { |
| 40 | + // this eval executes code supplied by user on their own machine, this is safe |
| 41 | + // eslint-disable-next-line no-eval |
| 42 | + eval(`parsedParams = ${methodParams}`) |
| 43 | + } catch (err) { |
| 44 | + throw new Error(`Invalid params: ${methodParams}`) |
| 45 | + } |
| 46 | + |
| 47 | + if (typeof parsedParams !== 'object') { |
| 48 | + throw new Error(`Invalid params: ${methodParams}`) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +print(`API: ${methodName}():`) |
| 53 | + |
| 54 | +// @ts-ignore |
| 55 | +typeformAPI[property][method](parsedParams) |
| 56 | + .then((result: Object) => { |
| 57 | + print(inspect(result, { showHidden: false, depth: null, colors: true })) |
| 58 | + }) |
| 59 | + .catch((err: Error) => { |
| 60 | + print(`Error: ${err.message}`) |
| 61 | + }) |
0 commit comments