@nestjs/common#ArgumentMetadata TypeScript Examples

The following examples show how to use @nestjs/common#ArgumentMetadata. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: global-validation.pipe.ts    From aqualink-app with MIT License 6 votes vote down vote up
async transform(value: any, metadata: ArgumentMetadata) {
    const originalTransform = this.isTransformEnabled;

    // Check if we should skip transforms for this param
    if (
      metadata &&
      metadata.type === 'param' &&
      metadata.data &&
      this.skipTransformIds.includes(metadata.data)
    ) {
      this.isTransformEnabled = false;
    }

    try {
      return super.transform(value, metadata);
    } finally {
      this.isTransformEnabled = originalTransform;
    }
  }
Example #2
Source File: validation.pipe.ts    From postgres-nest-react-typescript-boilerplate with GNU General Public License v3.0 6 votes vote down vote up
async transform(value: any, { metatype }: ArgumentMetadata) {
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length) {
      console.log(this.formatErrors(errors));
      throw new HttpException(
        `Validation error :  ${this.formatErrors(errors)}`,
        HttpStatus.BAD_REQUEST,
      );
    }
    return value;
  }
Example #3
Source File: validation.pipe.ts    From nestjs-starter with MIT License 6 votes vote down vote up
async transform(value, metadata: ArgumentMetadata) {
    if (!value) {
      throw new BadRequestException('No data submitted');
    }

    const { metatype } = metadata;
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
      throw new BadRequestException(this.buildError(errors), 'Input data validation failed');
    }
    return value;
  }
Example #4
Source File: joi.pipe.ts    From nestjs-joi with MIT License 6 votes vote down vote up
transform(payload: unknown, metadata: ArgumentMetadata): unknown {
    const schema = this.getSchema(metadata);

    if (!schema) {
      // This happens when a metatype was passed by NestJS and it has no
      // validation decoration.
      return payload;
    }

    return JoiPipe.validate(
      payload,
      schema,
      this.pipeOpts.usePipeValidationException,
      this.pipeOpts.skipErrorFormatting,
      // It is technically impossible for this to be undefined since it is explicitely assigned
      // with a default value in parseOptions(), so it is almost impossible to test.
      /* istanbul ignore next */
      this.pipeOpts.defaultValidationOptions || DEFAULT_JOI_OPTS,
      metadata,
    );
  }
Example #5
Source File: joi.pipe.ts    From nestjs-joi with MIT License 6 votes vote down vote up
/**
   * Determine what schema to return/construct based on the actual metadata
   * passed for this request.
   *
   * @param metadata
   */
  private getSchema(metadata: ArgumentMetadata): Joi.Schema | undefined {
    // If called in request scope mode, give preference to this mode.
    if (this.method && metadata.metatype) {
      let group: JoiValidationGroup | undefined;
      if (this.method === 'PUT' || this.method === 'PATCH') {
        group = JoiValidationGroups.UPDATE;
      } else if (this.method === 'POST') {
        group = JoiValidationGroups.CREATE;
      }

      return JoiPipe.getTypeSchema(metadata.metatype, { group });
    }

    // Prefer a static schema, if specified
    if (this.schema) {
      return this.schema;
    }

    // Prefer a static model, if specified
    if (this.type) {
      // Don't return "no schema" (undefined) if a type was explicitely specified
      return JoiPipe.getTypeSchema(this.type, { forced: true, group: this.pipeOpts.group });
    }

    // Determine the schema from the passed model
    if (metadata.metatype) {
      return JoiPipe.getTypeSchema(metadata.metatype, { group: this.pipeOpts.group });
    }

    return undefined;
  }
Example #6
Source File: validation.pipe.ts    From nestjs-starter with MIT License 6 votes vote down vote up
public async transform(value, metadata: ArgumentMetadata) {
    try {
      return await super.transform(value, metadata);
    } catch (e) {
      if (e instanceof BadRequestException) {
        const response: any = e.getResponse(); // TODO remove any
        const messages = response.message
          .map(message =>
            message.constraints ? Object.values(message.constraints) : message,
          )
          .flat();
        this.logger.error(JSON.stringify(messages));

        throw new BadRequestException(messages);
      }
    }
  }
Example #7
Source File: user-by-id.pipe.ts    From nestjs-mercurius with MIT License 5 votes vote down vote up
transform(value: string, metadata: ArgumentMetadata) {
    UserByIdPipe.REQUEST_SCOPED_DATA.push(this.requestId);
    return this.usersService.findById(value);
  }
Example #8
Source File: parse-date.pipe.ts    From aqualink-app with MIT License 5 votes vote down vote up
transform(value: string | undefined, metadata: ArgumentMetadata) {
    if (!isUndefined(value) && !isISO8601(value)) {
      throw new BadRequestException(`Date '${metadata.data}' is not valid`);
    }

    return value;
  }
Example #9
Source File: parse-object-id.pipe.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
transform(value: string, metadata: ArgumentMetadata) {
    if (!mongoose.isValidObjectId(value)) {
      throw new BadRequestException(`$value is not a valid mongoose object id`);
    }
    return value;
  }
Example #10
Source File: form.by.id.pipe.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
async transform(value: string, metadata: ArgumentMetadata): Promise<FormEntity> {
    const id = this.idService.decode(value)

    return await this.formService.findById(id)
  }
Example #11
Source File: submission.by.id.pipe.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
async transform(value: string, metadata: ArgumentMetadata): Promise<SubmissionEntity> {
    const id = this.idService.decode(value)

    return await this.submissionService.findById(id)
  }
Example #12
Source File: user.by.id.pipe.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
async transform(value: string, metadata: ArgumentMetadata): Promise<UserEntity> {
    const id = this.idService.decode(value)

    return await this.userService.findById(id)
  }
Example #13
Source File: stripUndefined.pipe.ts    From office-hours with GNU General Public License v3.0 5 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  transform(value: any, metadata: ArgumentMetadata): any {
    if (metadata.type === 'body') {
      this.dropUndefined(value);
      return value;
    }
    return value;
  }
Example #14
Source File: joi.pipe.ts    From nestjs-joi with MIT License 5 votes vote down vote up
// Called "validate" and NOT "transform", because that would make it match
  // the interface of a pipe INSTANCE and prevent NestJS from recognizing it as
  // a class constructor instead of an instance.
  private static validate<T>(
    payload: unknown,
    schema: Joi.Schema,
    usePipeValidationException: boolean,
    skipErrorFormatting: boolean,
    validationOptions: Joi.ValidationOptions,
    /* istanbul ignore next */
    metadata: ArgumentMetadata = { type: 'custom' },
  ): T {
    const { error, value } = schema.validate(
      payload,
      // This will always get overridden by whatever options have been specified
      // on the schema itself
      validationOptions,
    );

    if (error) {
      // Fixes #4
      if (Joi.isError(error)) {
        // Provide a special response with reasons
        const reasons = error.details
          .map((detail: { message: string }) => detail.message)
          .join(', ');
        const formattedMessage =
          `Request validation of ${metadata.type} ` +
          (metadata.data ? `item '${metadata.data}' ` : '') +
          `failed, because: ${reasons}`;
        if (usePipeValidationException) {
          throw new JoiPipeValidationException(
            skipErrorFormatting ? error.message : formattedMessage,
          );
        } else {
          throw new BadRequestException(skipErrorFormatting ? error : formattedMessage);
        }
      } else {
        // If error is not a validation error, it is probably a custom error thrown by the schema.
        // Pass it through to allow it to be caught by custom error handlers.
        throw error;
      }
    }

    // Everything is fine
    return value as T;
  }