How to use @adonisjs/utils - 10 common examples

To help you get started, we’ve selected a few @adonisjs/utils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github adonisjs / adonis-framework / packages / bodyparser / src / Multipart / processMultipart.ts View on Github external
await streamFile(part, tmpPath, (line: Buffer) => {
      const size = line.length
      bytes += size
      totalBytes += size

      /**
       * Ensure request data isn't getting over the defined limit. Otherwise,
       * we need to raise an exception
       */
      if (totalBytes > config.limit) {
        part.emit(
          'error',
          new Exception('request entity too large', 413, exceptionCodes.E_REQUEST_ENTITY_TOO_LARGE),
        )
      }
    })
github adonisjs / adonis-framework / packages / server / src / routePreProcessor.ts View on Github external
/**
     * 1. Do not prepend namespace, if `namespace` starts with `/`.
     * 2. Else if `namespace` exists, then prepend the namespace
     */
    if (route.handler.startsWith('/')) {
      handler = route.handler.substr(1)
    } else if (route.meta.namespace) {
      handler = `${route.meta.namespace.replace(/\/$/, '')}/${route.handler}`
    }

    /**
     * Split the controller and method. Raise error if `method` is missing
     */
    const [ namespace, method ] = handler.split('.')
    if (!method) {
      throw new Exception(
        `Missing controller method on \`${route.pattern}\` route`,
        500,
        exceptionCodes.E_INVALID_ROUTE_NAMESPACE,
      )
    }

    /**
     * Unlike middleware, we do not prefetch controller from the IoC container
     * since controllers in an app can grow to a huge number and lazy loading
     * them improves the performance overall.
     *
     * Sometime later, we can introduce `hot cache` in IoC container, which
     * avoids lookup cost within the IoC container.
     */
    route.meta.resolvedHandler = {
      type: 'class',
github adonisjs / adonis-framework / packages / core / providers / AppProvider.ts View on Github external
private _getAppKey (): string {
    const appKey = this.$container.use('Adonis/Src/Config').get('app.appKey')
    if (!appKey) {
      throw new Exception('Define appKey inside config/app file', 500, exceptionCodes.E_MISSING_APP_KEY)
    }
    return appKey
  }
github adonisjs / adonis-framework / packages / router / src / Router.ts View on Github external
public group (callback: () => void): RouteGroup {
    if (this._inGroup) {
      throw new Exception('Cannot create nested route groups', 500, exceptionCodes.E_NESTED_ROUTE_GROUPS)
    }

    /**
     * Set the flag that we are in a group
     */
    this._inGroup = true

    /**
     * Execute the callback. Now all registered routes will be
     * collected seperately from the `routes` array
     */
    callback()

    /**
     * Create a new group and pass all the routes
     */
github adonisjs / adonis-framework / packages / server / src / MiddlewareStore.ts View on Github external
if (typeof (item) === 'function') {
        return { type: 'function', value: item, args: [] }
      }

      /**
       * Extract middleware name and args from the string
       */
      const [ { name, args } ] = haye.fromPipe(item).toArray()

      /**
       * Get resolved node for the given name and raise exception when that
       * name is missing
       */
      const resolvedMiddleware = this.getNamed(name)
      if (!resolvedMiddleware) {
        throw new Exception(`Cannot find named middleware ${name}`, 500, exceptionCodes.E_MISSING_NAMED_MIDDLEWARE)
      }

      resolvedMiddleware.args = args
      return resolvedMiddleware
    })
  }
github adonisjs / adonis-framework / packages / router / src / Store.ts View on Github external
route.methods.forEach((method) => {
      const methodRoutes = this._getMethodRoutes(route.domain || 'root', method)

      /**
       * Ensure that route doesn't pre-exists. In that case, we need to throw
       * the exception, since it's a programmer error to create multiple
       * routes with the same pattern.
       */
      if (methodRoutes.routes[route.pattern]) {
        throw new Exception(`Duplicate route \`${method}:${route.pattern}\``, 500, exceptionCodes.E_DUPLICATE_ROUTE)
      }

      /**
       * Generate tokens for the given route and push to the list
       * of tokens
       */
      methodRoutes.tokens.push(matchit.parse(route.pattern, route.matchers))

      /**
       * Store reference to the route, so that we can return it to the user, when
       * they call `match`.
       */
      methodRoutes.routes[route.pattern] = routeJSON
    })
github adonisjs / adonis-framework / packages / core / src / Env / index.ts View on Github external
private _load (filePath: string, overwrite: boolean): { error: Error | null } {
    const absPath = isAbsolute(filePath) ? filePath : join(this._appRoot, filePath)
    let contents = ''

    /**
     * Read file synchronously
     */
    try {
      contents = readFileSync(absPath, this._encoding)
    } catch (error) {
      const exception = error.code === 'ENOENT'
        ? new Exception(`The ${filePath} file is missing`, 500, 'E_MISSING_ENV_FILE')
        : error

      return { error: exception }
    }

    /**
     * Parse file contents as `.env`. There is no need to catch `parse` exceptions. If file
     * content is invalid, we must let the process fail
     */
    const envCollection = dotenv.parse(contents.trim())

    /**
     * Overwrite the process.env variables by looping
     * over the collection
     */
    Object.keys(envCollection).forEach((key) => {
github adonisjs / adonis-framework / packages / router / src / Group.ts View on Github external
function missingRouteName () {
  return new Exception(
    'All routes inside a group must have names before calling Route.group.as',
    500,
    exceptionCodes.E_MISSING_ROUTE_NAME,
  )
}
github adonisjs / adonis-framework / packages / bodyparser / src / BodyParser / index.ts View on Github external
private _getExceptionFor (error) {
    switch (error.type) {
      case 'encoding.unsupported':
        return new Exception(error.message, error.status, 'E_ENCODING_UNSUPPORTED')
      case 'entity.too.large':
        return new Exception(error.message, error.status, 'E_REQUEST_ENTITY_TOO_LARGE')
      case 'request.aborted':
        return new Exception(error.message, error.status, 'E_REQUEST_ABORTED')
      default:
        return error
    }
  }
github adonisjs / adonis-framework / packages / fold / src / Registrar / index.ts View on Github external
private _loadProvider (providerPath: string) {
    const provider = tsRequire(providerPath)
    return new provider(this.ioc)
  }

@adonisjs/utils

A collection of utilities to keep AdonisJs codebase dry

MIT
Latest version published 5 years ago

Package Health Score

67 / 100
Full package analysis