How to use @ditojs/utils - 10 common examples

To help you get started, we’ve selected a few @ditojs/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 ditojs / dito / packages / server / src / cli / index.js View on Github external
async function execute() {
  try {
    // Dynamically load app or config from the path provided package.json script
    const [,, command, importPath, ...args] = process.argv
    const execute = command && getCommand(commands, command.split(':'))
    if (!isFunction(execute)) {
      throw new Error(`Unknown command: ${command}`)
    }
    let arg = (await import(path.resolve(importPath))).default
    if (isFunction(arg)) {
      arg = await arg()
    } else if (isPlainObject(arg) && arg.knex) {
      arg = Knex(arg.knex)
    }
    const res = await execute(arg, ...args)
    process.exit(res === true ? 0 : 1)
  } catch (err) {
    if (err instanceof Error) {
      console.error(
        chalk.red(`${err.detail ? `${err.detail}\n` : ''}${err.stack}`)
      )
    } else {
github ditojs / dito / packages / server / src / cli / index.js View on Github external
async function execute() {
  try {
    // Dynamically load app or config from the path provided package.json script
    const [,, command, importPath, ...args] = process.argv
    const execute = command && getCommand(commands, command.split(':'))
    if (!isFunction(execute)) {
      throw new Error(`Unknown command: ${command}`)
    }
    let arg = (await import(path.resolve(importPath))).default
    if (isFunction(arg)) {
      arg = await arg()
    } else if (isPlainObject(arg) && arg.knex) {
      arg = Knex(arg.knex)
    }
    const res = await execute(arg, ...args)
    process.exit(res === true ? 0 : 1)
  } catch (err) {
    if (err instanceof Error) {
      console.error(
        chalk.red(`${err.detail ? `${err.detail}\n` : ''}${err.stack}`)
      )
    } else {
      console.error(chalk.red(err))
    }
    process.exit(1)
  }
}
github ditojs / dito / packages / server / src / cli / db / createMigration.js View on Github external
const statement = primary
        ? [`table.increments('${column}').primary()`]
        : specificType
          ? [`table.specificType('${column}', '${specificType}')`]
          : [`table.${knexType}('${column}')`]
      statement.push(
        unsigned && 'unsigned()',
        !primary && required && 'notNullable()',
        nullable && 'nullable()',
        unique && 'unique()',
        index && 'index()'
      )
      if (_default !== undefined) {
        let value = defaultValues[_default]
        if (!value) {
          value = isArray(_default) || isObject(_default)
            ? JSON.stringify(_default)
            : _default
          if (isString(value)) {
            value = `'${value}'`
          }
        }
        statement.push(`defaultTo(${value})`)
      }
      if (foreign) {
        for (const relation of Object.values(relations)) {
          // TODO: Support composite keys for foreign references:
          // Use `asArray(from)`, `asArray(to)`
          const { from, to, owner } = relation
          const [fromClass, fromProperty] = from?.split('.') || []
          if (fromProperty === name) {
            if (fromClass !== modelClass.name) {
github ditojs / dito / packages / server / src / query / QueryBuilder.js View on Github external
getPropertyRefs(refs, { parseDir = false, checkAllowed = true } = {}) {
    refs = isString(refs) ? refs.split(/\s*\|\s*/) : refs
    const cache = this._propertyRefsCache
    // Pass on _propertyRefsAllowed to make sure there are only allowed
    // properties in the query parameters.
    return refs.map(ref => cache[ref] ||
      (cache[ref] = new PropertyRef(ref, this.modelClass(), parseDir,
        checkAllowed && this._propertyRefsAllowed)))
  }
github ditojs / dito / packages / admin / src / components / DitoSchema.vue View on Github external
showValidationErrors(errors, focus) {
      this.clearErrors()
      let first = true
      const unmatched = []
      for (const [dataPath, errs] of Object.entries(errors)) {
        // If the schema is a data-root, prefix its own dataPath to all errors,
        // since the data that it sends and validates will be unprefixed.
        const fullDataPath = this.hasOwnData
          ? appendDataPath(this.dataPath, dataPath)
          : dataPath
        // console.log(this, this.dataPath, this.hasOwnData, fullDataPath)
        // Convert from JavaScript property access notation, to our own form
        // of relative JSON pointers as data-paths:
        const dataPathParts = parseDataPath(fullDataPath)
        const component = this.getComponent(dataPathParts)
        if (!component?.showValidationErrors(errs, first && focus)) {
          // Couldn't find a component in an active form for the given dataPath.
          // See if we can find a component serving a part of the dataPath,
          // and take it from there:
          const property = dataPathParts.pop()
          while (dataPathParts.length > 0) {
            const component = this.getComponent(dataPathParts)
            if (component?.navigateToComponent?.(fullDataPath, routeRecord => {
              // Filter the errors to only contain those that belong to the
              // matched dataPath:
              const normalizedPath = normalizeDataPath(dataPathParts)
              // Pass on the errors to the instance through the meta object,
              // see DitoForm.created()
              routeRecord.meta.errors = Object.entries(errors).reduce(
                (filtered, [dataPath, errs]) => {
github ditojs / dito / packages / admin / src / components / DitoForm.vue View on Github external
sourceData() {
      // Possible parents are DitoForm for forms, or DitoView for root lists.
      // Both have a data property which abstracts away loading and inheriting
      // of data.
      let { data } = this.parentRouteComponent
      if (data) {
        // Handle nested data by splitting the dataPath, iterate through the
        // actual data and look nest child-data up.
        const dataParts = parseDataPath(
          this.getDataPathFrom(this.parentRouteComponent)
        )
        // Compare dataParts against matched routePath parts, to identify those
        // parts that need to be treated like ids and mapped to indices in data.
        const pathParts = this.routeRecord.path.split('/')
        const routeParts = pathParts.slice(pathParts.length - dataParts.length)
        this.sourceKey = null
        const lastDataPart = dataParts[dataParts.length - 1]
        if (isObjectSource(this.sourceSchema) && lastDataPart === 'create') {
          // If we have an object source and are creating, the dataPath needs to
          // be shortened by the 'create' entry. This isn't needed for list
          // sources, as there the parameter is actually mapped to the item id.
          dataParts.length--
        }
        for (let i = 0, l = dataParts.length; i < l && data; i++) {
          const dataPart = dataParts[i]
github ditojs / dito / packages / server / src / cli / db / createMigration.js View on Github external
const { relations } = modelClass.definition
  for (const relation of Object.values(relations)) {
    const { from, to, inverse } = relation
    const relationClass = getRelationClass(relation.relation)
    if (isThroughRelationClass(relationClass) && !inverse) {
      // TODO: Support composite keys for foreign references:
      // Use `asArray(from)`, `asArray(to)`
      const [fromClass, fromProperty] = from?.split('.') || []
      const [toClass, toProperty] = to?.split('.') || []
      const statements = []
      // See convertRelations()
      const tableName = app.normalizeIdentifier(`${fromClass}${toClass}`)
      const fromId = app.normalizeIdentifier(
        `${fromClass}${capitalize(fromProperty)}`)
      const toId = app.normalizeIdentifier(
        `${toClass}${capitalize(toProperty)}`)
      tables.push({ tableName, statements })
      statements.push(`table.increments('id').primary()`)
      statements.push(deindent`
        table.integer('${fromId}').unsigned().index()
          .references('${app.normalizeIdentifier(fromProperty)}')\\
          .inTable('${app.normalizeIdentifier(fromClass)}')\\
          .onDelete('CASCADE')`)
      statements.push(deindent`
        table.integer('${toId}').unsigned().index()
          .references('${app.normalizeIdentifier(toProperty)}')\\
          .inTable('${app.normalizeIdentifier(toClass)}')\\
          .onDelete('CASCADE')`)
    }
  }
}
github ditojs / dito / packages / server / src / cli / db / createMigration.js View on Github external
async function collectThroughTables(modelClass, app, tables) {
  const { relations } = modelClass.definition
  for (const relation of Object.values(relations)) {
    const { from, to, inverse } = relation
    const relationClass = getRelationClass(relation.relation)
    if (isThroughRelationClass(relationClass) && !inverse) {
      // TODO: Support composite keys for foreign references:
      // Use `asArray(from)`, `asArray(to)`
      const [fromClass, fromProperty] = from?.split('.') || []
      const [toClass, toProperty] = to?.split('.') || []
      const statements = []
      // See convertRelations()
      const tableName = app.normalizeIdentifier(`${fromClass}${toClass}`)
      const fromId = app.normalizeIdentifier(
        `${fromClass}${capitalize(fromProperty)}`)
      const toId = app.normalizeIdentifier(
        `${toClass}${capitalize(toProperty)}`)
      tables.push({ tableName, statements })
      statements.push(`table.increments('id').primary()`)
      statements.push(deindent`
        table.integer('${fromId}').unsigned().index()
          .references('${app.normalizeIdentifier(fromProperty)}')\\
          .inTable('${app.normalizeIdentifier(fromClass)}')\\
          .onDelete('CASCADE')`)
      statements.push(deindent`
        table.integer('${toId}').unsigned().index()
          .references('${app.normalizeIdentifier(toProperty)}')\\
          .inTable('${app.normalizeIdentifier(toClass)}')\\
          .onDelete('CASCADE')`)
    }
  }
github ditojs / dito / packages / admin / src / components / DitoForm.vue View on Github external
buttonSchemas() {
      return getButtonSchemas(
        merge(
          {
            cancel: {
              type: 'button',
              events: {
                click: () => this.cancel()
              }
            },

            submit: !this.doesMutate && {
              type: 'submit',
              // Submit buttons close the form by default:
              closeForm: true,
              events: {
                click: ({ target }) => target.submit()
              }
            }
github ditojs / dito / packages / server / src / app / Validator.js View on Github external
const schema = clone(jsonSchema, value => {
      if (isObject(value)) {
        if (patch) {
          // Remove all required keywords and formats from schema for patch
          // validation.
          delete value.required
          if (value.format === 'required') {
            delete value.format
          }
        }
        // Convert async `validate()` keywords to `validateAsync()`:
        if (isAsync(value.validate)) {
          value.validateAsync = value.validate
          delete value.validate
        }
        if (!async) {
          // Remove all async keywords for synchronous validation.
          for (const key in value) {