All files / src utils.ts

68.42% Statements 52/76
35.71% Branches 5/14
50% Functions 6/12
64.71% Lines 44/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 1453x 3x 3x   3x   3x     36x   2x 2x   2x 2x   2x 2x   2x 2x     28x 28x     36x 36x   36x 96x     36x   36x     3x 2x 2x     3x                     3x                                   3x       2x   2x 36x   36x     2x     3x 4x   4x       4x               4x                         4x       4x     3x 2x 2x                               2x    
import * as chalk from 'chalk'
import * as boxen from 'boxen'
import { Validator, ValidatorResult } from 'jsonschema'
 
import Restapify, { RestapifyParams, HttpVerb, RestapifyErrorName } from 'restapify'
 
export const getMethodOutput = (method: HttpVerb): string => {
  let methodOutput
 
  switch (method) {
  case 'DELETE':
    methodOutput = chalk.red
    break
  case 'POST':
    methodOutput = chalk.yellow
    break
  case 'PUT':
    methodOutput = chalk.blue
    break
  case 'PATCH':
    methodOutput = chalk.gray
    break
 
  default: case 'GET':
    methodOutput = chalk.green
    break
  }
 
  let methodName = method
  let methodNameLength = method.length
 
  for (let index = 0; index < (6 - methodNameLength); index += 1) {
    methodName += ' '
  }
 
  methodOutput = methodOutput.bold(`${methodName}`)
 
  return methodOutput
}
 
export const consoleError = (message: string): void => {
  const errorPrepend = chalk.red.bold.underline('❌ERROR:')
  console.log(`${errorPrepend} ${message}`)
}
 
export const getInstanceOverviewOutput = (port: number, apiBaseURL: string): string => {
  const runningTitle = chalk.magenta('🚀 Restapify is running:')
  const apiBaseURLTitle = chalk.bold('- 📦API base url:')
  const apiBaseURLLink = chalk.blueBright(`http://localhost:${port}${apiBaseURL}`)
  const dashboardURLTitle = chalk.bold('- 🎛 Dashboard:')
  const dashboardURLLink = chalk.blueBright(`http://localhost:${port}/restapify`)
  const apiBaseURLOutput = `${apiBaseURLTitle} ${apiBaseURLLink}`
  const dashboardURLOutput = `${dashboardURLTitle} ${dashboardURLLink}`
  return boxen(`${runningTitle}\n\n${apiBaseURLOutput}\n${dashboardURLOutput} `, { padding: 1, borderColor: 'magenta' })
}
 
export const onRestapifyInstanceError = (
  error: RestapifyErrorName,
  instanceData: Pick<Restapify, 'apiBaseUrl' | 'port' | 'rootDir'>
): void => {
  const { rootDir, port, apiBaseUrl } = instanceData
 
  if (error.startsWith('MISS:ROOT_DIR')) {
    consoleError(`The given folder ${rootDir} doesn't exist!`)
  } else if (error.startsWith('MISS:PORT')) {
    consoleError(`port ${port} is already in use!`)
  } else if (error.startsWith('INV:API_BASEURL')) {
    consoleError(`Impossible to use ${apiBaseUrl} as the API base URL since it's already needed for internal purposes!`)
  } else if (error.startsWith('INV:JSON_FILE')) {
    const filePath = error.split(' ')[1]
    consoleError(`Impossible to parse the JSON file ${filePath}!`)
  }
}
 
export const getRoutesListOutput = (
  routesList: { route: string; method: HttpVerb; }[],
  apiBaseUrl: string
): string => {
  let output = ''
 
  routesList.forEach(servedRoute => {
    let methodOutput = getMethodOutput(servedRoute.method)
 
    output += `\n${methodOutput} ${apiBaseUrl}${servedRoute.route}`
  })
 
  return output
}
 
export const runServer = (config: RestapifyParams): void => {
  const RestapifyInstance = new Restapify(config)
 
  RestapifyInstance.on('server:start', () => {
    console.log(`\n🏗 Try to serve on port ${RestapifyInstance.port}`)
  })
 
  RestapifyInstance.onError(({ error }) => {
    onRestapifyInstanceError(error, {
      rootDir: RestapifyInstance.rootDir,
      apiBaseUrl: RestapifyInstance.apiBaseUrl,
      port: RestapifyInstance.port
    })
  })
 
  RestapifyInstance.on('start', () => {
    const servedRoutesOutput = getRoutesListOutput(
      RestapifyInstance.getServedRoutes(),
      RestapifyInstance.apiBaseUrl
    )
 
    console.log(servedRoutesOutput)
    console.log(getInstanceOverviewOutput(
      RestapifyInstance.port,
      RestapifyInstance.apiBaseUrl
    ))
  })
 
  RestapifyInstance.on('server:restart', () => {
    console.log(chalk.green('✅ API updated!'))
  })
 
  RestapifyInstance.run()
}
 
export const validateConfig = (config: object): ValidatorResult => {
  const jsonValidor = new Validator()
  const CONFIG_FILE_SCHEMA = {
    type: 'object',
    rootDir: { type: 'string' },
    apiBaseUrl: { type: 'string' },
    port: { type: 'number' },
    states: {
      properties: {
        route: 'string',
        method: 'string',
        state: 'string'
      },
      required: ['route', 'method', 'state']
    },
    required: ['rootDir']
  }
 
  return jsonValidor.validate(config, CONFIG_FILE_SCHEMA)
}