All files / src decorators.ts

100% Statements 95/95
100% Branches 30/30
100% Functions 14/14
100% Lines 94/94

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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248  1x 1x   1x 1x   1x 1x                         1x 1x                     2x   2x         10x 10x   10x 5x     5x 5x     5x   5x     2x   2x 10x 9x   9x 4x     5x 5x   5x 2x     3x 3x   1x   1x 1x 1x 1x 1x       1x       5x 3x                 1x 2x 2x 1x   1x                   1x 3x 1x 1x     2x 1x     1x                         23x 23x 10x               13x                 15x   15x 4x     11x 6x     5x 5x                 1x 11x 11x 1x           10x 10x 10x   10x 1x               9x 9x     9x 9x   9x     19x 19x 35x 35x       19x 19x 67x 5x   5x   5x 3x         17x     10x 18x 18x       10x   10x   7x          
import * as mage from 'mage'
import * as classTransformer from 'class-transformer'
import * as classValidator from 'class-validator'
 
import { ValidatedTopic } from './classes'
import { crash, ValidationError } from './errors'
 
const deepIterator = require('deep-iterator').default
const functionArguments = require('function-arguments')
 
/**
 * usercommand.execute function signature
 */
type IExecuteFunction = <T>(state: mage.core.IState, ...args: any[]) => Promise<T>
 
/**
 * Validate function type (currently used for MapOf)
 */
export type ValidateFunction = (key: string, value: any) => void
 
// Expose everything from class-validator and class-transformer
export * from 'class-transformer'
export * from 'class-validator'
 
/**
 * wrap the class' static create method
 *
 * @param target
 * @param key
 * @param childrenType
 * @param type
 */
function wrapCreate(target: any, key: string, childrenType: any, validateFunction?: ValidateFunction, mapType?: any) {
  const { create } = target
 
  target.create = async (
    state: mage.core.IState,
    index: mage.archivist.IArchivistIndex,
    data?: any
  ) => {
    const instance = await create.call(target, state, index, data)
    const map = mapType ? new mapType() : {}
 
    if (!instance[key]) {
      return instance
    }
 
    for (const [subkey, value] of Object.entries(instance[key])) {
      map[subkey] = Object.assign(new childrenType(), value)
    }
 
    instance[key] = map
 
    return instance
  }
 
  const { validate } = target.prototype
 
  target.prototype.validate = async function (errorMessage?: string, code?: string) {
    await validate.call(this, errorMessage, code)
    let errors: any[] = []
 
    if (!this[key]) {
      return
    }
 
    for (const [subkey, value] of Object.entries(this[key])) {
      errors = errors.concat(await classValidator.validate(value))
 
      if (!validateFunction) {
        continue
      }
 
      try {
        validateFunction(subkey, value)
      } catch (error) {
        error.message = `Validation error on ${key}.${subkey}: ${error.message}`
 
        const validationError = new classValidator.ValidationError()
        validationError.target = target
        validationError.property = key
        validationError.value = value
        validationError.constraints = {
          mapOf: error.message
        }
 
        errors.push(Object.assign(validationError, error))
      }
    }
 
    if (errors.length > 0) {
      this.raiseValidationError(errors, errorMessage, code)
    }
  }
}
 
/**
 *
 * @param type
 */
export function MapOf(type: any, validateFunction?: ValidateFunction) {
  return (target: any, key?: string) => {
    if (!key) {
      target.isMapOf = { type, validateFunction }
    } else {
      wrapCreate(target.constructor, key, type, validateFunction)
    }
  }
}
 
/**
 * Wrap @Type from class-transformer
 *
 * @param type The type to configure
 */
export function Type(type: any) {
  if (type.isMapOf) {
    const { type: childrenType, validateFunction } = type.isMapOf
    return (target: any, key: string) => wrapCreate(target.constructor, key, childrenType, validateFunction, type)
  }
 
  if (type.prototype) {
    return classTransformer.Type(/* istanbul ignore next */ () => type)
  }
 
  return classTransformer.Type(type)
}
 
/**
 * Validate ValidatedObjects and throw an error if the data is invalid.
 *
 * @param message
 * @param code
 * @param state
 * @param parsedData
 * @param receivedData
 */
async function validateObject(message: string, code: string, state: any, parsedData: any, receivedData?: any) {
  const errors = await classValidator.validate(parsedData)
  if (errors.length > 0) {
    throw new ValidationError(message, code, {
      actorId: state.actorId,
      userCommand: state.description,
      receivedData,
      parsedData
    }, errors)
  }
 
  return parsedData
}
 
/**
 * Validate the output of an `execute` call of an user command.
 *
 * @param value
 */
async function validateOutput(state: mage.core.IState, value: any) {
  const type = typeof value
 
  if (type !== 'object') {
    return
  }
 
  if (!Array.isArray(value)) {
    return validateObject('Invalid user command return value', 'server', state, value)
  }
 
  for (const val of value) {
    await validateOutput(state, val)
  }
}
 
/**
 * @Acl decorator
 *
 * Protect the user command with the given ACL and defined type validation
 */
export function Acl(...acl: string[]) {
  return function (UserCommand: any, key: string) {
    if (key !== 'execute') {
      throw crash('@validate only works for usercommand.execute functions', {
        method: key,
        userCommand: UserCommand
      })
    }
 
    const execute = <IExecuteFunction> UserCommand.execute
    const parameterNames = functionArguments(execute)
    const types = Reflect.getMetadata('design:paramtypes', UserCommand, key)
 
    if (!types) {
        throw crash('Reflect.getMetadata returned null.\
        Did you set experimentalDecorators and emitDecoratorMetadata to true in your tsconfig.json ?', {
            method: key,
            userCommand: UserCommand
        })
    }
 
    // We extract the state information, since we won't need it
    parameterNames.shift()
    types.shift()
 
    // We attach additional information to the UserCommand class
    UserCommand.acl = acl
    UserCommand.params = parameterNames
 
    return {
      value: async (state: mage.core.IState, ...args: any[]) => {
        // Map user command's parameters
        const userCommandData: { [key: string]: any } = {}
        args.forEach((arg, pos) => {
          const parameterName = parameterNames[pos]
          userCommandData[parameterName] = arg
        })
 
        // Cast data into a user command instance
        const userCommand = classTransformer.plainToClass(UserCommand, userCommandData)
        for (const { value } of deepIterator(userCommand)) {
          if (value instanceof ValidatedTopic) {
            value.setState(state)
 
            const index = (<any> value).index || {}
 
            await value.setIndex(index)
            delete (<any> value).index
          }
        }
 
        // Validate all parameters at once
        await validateObject('Invalid user command input', 'invalidInput', state, userCommand, userCommandData)
 
        // Map casted parameters into an array of arguments
        const castedArgs = args.map((_arg, pos) => {
          const parameterName = parameterNames[pos]
          return (<any> userCommand)[parameterName]
        })
 
        // Execute the actual user command
        const output = await execute(state, ...castedArgs)
 
        await validateOutput(state, output)
 
        return output as any
      }
    }
  }
}