class-transformer#plainToInstance TypeScript Examples

The following examples show how to use class-transformer#plainToInstance. 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: map-class.ts    From Discord-Bot-TypeScript-Template with MIT License 9 votes vote down vote up
export function mapClass(cls: ClassConstructor<object>): RequestHandler {
    return async (req: Request, res: Response, next: NextFunction) => {
        // Map to class
        let obj: object = plainToInstance(cls, req.body);

        // Validate class
        let errors = await validate(obj, {
            skipMissingProperties: true,
            whitelist: true,
            forbidNonWhitelisted: false,
            forbidUnknownValues: true,
        });
        if (errors.length > 0) {
            res.status(400).send({ error: true, errors: formatValidationErrors(errors) });
            return;
        }

        // Set validated class to locals
        res.locals.input = obj;
        next();
    };
}
Example #2
Source File: AlertService.ts    From viewer-components-react with MIT License 8 votes vote down vote up
private getAlerts$(sensorId: string): Observable<Alert[]> {
    return ApiService.sendRequest$(
      this.endpoints.getAlerts,
      "GET",
      { params: { entityId: sensorId } }
    ).pipe(
      tap((data: any) => LoggerService.log("Received alerts for sensor:", data)),
      map((data: {alerts: object[]}) => {
        const alerts: Alert[] = [];
        if (data.alerts && data.alerts.length) {
          _forEach(data.alerts, (alertData: {[key: string]: any}) => {
            if (alertData.alert) {
              const alert: Alert = plainToInstance(Alert, alertData.alert as object);
              if (alertData.lastTrigger) {
                const trigger: AlertTrigger = plainToInstance(AlertTrigger, alertData.lastTrigger as object);
                this.setTriggerDescription(trigger);
                alert.setLastTrigger(trigger);
              }
              alerts.push(alert);
            }
          });
        }
        return alerts;
      })
    );
  }
Example #3
Source File: EntityService.ts    From viewer-components-react with MIT License 6 votes vote down vote up
public getEntities$(entityType: EntityType, searchQuery: SearchQuery): Observable<(Node | Device | Sensor)[]> {
    return EntityTypeService.types$(entityType).pipe(
      first(),
      switchMap(() => {
        return ApiService.sendRequest$(
          this.getEndpoint("getEntities", entityType) as string,
          "GET",
          { params: searchQuery.getQueryParams() }
        ).pipe(
          tap((data: any) => LoggerService.log(`Received ${entityType}s:`, data)),
          catchError(() => of([])),
          map((data: object[]) => {

            // Update search query pagination parameters before we filter results
            searchQuery.checkResults(data.length);

            // Convert raw response to appropriate entity class
            return _map(data, (dataObject: object) => {
              return plainToInstance<Node | Device | Sensor, object>(this.getEntityClass(entityType), dataObject);
            });
          })
        );
      })
    );
  }
Example #4
Source File: EntityService.ts    From viewer-components-react with MIT License 6 votes vote down vote up
public getEntity$(entityType: EntityType, id: string): Observable<Node | Device | Sensor> {
    if (this.entityCache[entityType][id]) {
      return of(instanceToInstance(this.entityCache[entityType][id]));
    } else {
      return EntityTypeService.types$(entityType).pipe(
        first(),
        switchMap(() => {
          return ApiService.sendRequest$(this.getEndpoint("getEntity", entityType) as string + id)
            .pipe(
              tap((data: any) => LoggerService.log(`Received ${entityType}:`, data)),
              map((data: object) => {
                const entity = plainToInstance<Node | Device | Sensor, object>(this.getEntityClass(entityType), data);
                this.entityCache[entityType][id] = entity;
                return entity;
              })
            );
        })
      );
    }
  }
Example #5
Source File: EntityTypeService.ts    From viewer-components-react with MIT License 6 votes vote down vote up
private getTypes(entityType: EntityType): void {
    if (!this.retrievingTypes[entityType]) {
      this.retrievingTypes[entityType] = true;
      ApiService.sendRequest$(this.getEndpoint(entityType))
        .subscribe({
          next: (data: {[key: string]: any[]}) => {
            LoggerService.log("Received entity types for", entityType, ":", data);
            this.types[entityType].next(
              _chain(data[`${entityType}Types`])
                .keyBy((type: any) => type.id)
                .mapValues((type: object) => plainToInstance(EntityTypeMetadata, type))
                .value() as any
            );
          },
          error: () => {},
          complete: () => {
            this.retrievingTypes[entityType] = false;
          },
        }
        );
    }
  }
Example #6
Source File: IModelSettingsService.ts    From viewer-components-react with MIT License 6 votes vote down vote up
private loadSettings(): void {
    if (!this.initialized) {

      this.initialized = true;

      // Get current auth state because we need the project id
      AuthService.authState$()
        .pipe(
          filter((authState: AuthState | null) => !!authState),
          first()
        )
        .subscribe((authState: AuthState | null) => {
          if (authState) {
            ConfigSettingsService.getConfigSettings$(authState.getProjectId())
              .subscribe({
                next: ((data: {[key: string]: any }) => {
                  LoggerService.log("Loaded iModel settings:", data);
                  this.setIModelSettings(plainToInstance(IModelSettings, data), false);
                }),
                error: (() => {
                  this.setIModelSettings(new IModelSettings(), false);
                }),
              });
          } else {
            LoggerService.warn("Error saving iModel settings: Auth State not available");
            this.setIModelSettings(new IModelSettings(), false);
          }
        });
    }
  }
Example #7
Source File: ObservationService.ts    From viewer-components-react with MIT License 6 votes vote down vote up
private createObservationSet(entity: Sensor, observationQuery: ObservationQuery): ObservationSet {
    const metric = MetricService.getMetric(observationQuery.getMetric() as string);
    const unit = MetricService.getUnit(observationQuery.getUnit() as string);
    const observationSet = {
      entityId: entity.getId(),
      entityName: entity.getName(),
      entityType: entity.getType(),
      entityTypeReadable: entity.isSensor() ? EntityTypeService.getSensorTypeReadable(entity) : undefined,
      metricId: observationQuery.getMetric(),
      metricName: metric ? metric.getName() : observationQuery.getMetric(),
      unitId: observationQuery.getUnit(),
      unitName: unit ? unit.getName() : observationQuery.getUnit(),
      observationQuery,
      observations: [],
    };
    return plainToInstance(ObservationSet, observationSet);
  }
Example #8
Source File: pipe-transtorm.ts    From malagu with MIT License 5 votes vote down vote up
public async transform(value: any, metadata: ArgumentMetadata): Promise<any> {
        const opts = this.options || {};
        const { argType } = metadata;
        if (!argType || !this.toValidate(metadata)) {
            return value;
        }
        const originalValue = value;
        value = this.toEmptyIfNil(value);

        const isNil = value !== originalValue;
        const isPrimitive = this.isPrimitive(value);
        this.stripProtoKeys(value);
        let entity = plainToInstance(
            argType,
            value,
            opts.transformOptions,
        );

        const originalEntity = entity;
        const isCtorNotEqual = entity.constructor !== argType;

        if (isCtorNotEqual && !isPrimitive) {
            entity.constructor = argType;
        } else if (isCtorNotEqual) {
            // when "entity" is a primitive value, we have to temporarily
            // replace the entity to perform the validation against the original
            // metatype defined inside the handler
            entity = { constructor: argType } as any;
        }

        const errors = await validate(entity, opts.validatorOptions);
        if (errors.length > 0) {
            throw new ValidationErrors(opts.detailedOutputDisabled ? undefined : errors);
        }
        if (isPrimitive) {
            // if the value is a primitive value and the validation process has been successfully completed
            // we have to revert the original value passed through the pipe
            entity = originalEntity;
        }
        if (opts.transformEnabled) {
            return entity;
        }
        if (isNil) {
            // if the value was originally undefined or null, revert it back
            return originalValue;
        }
        return Object.keys(opts.validatorOptions).length > 0
            ? instanceToPlain(entity, opts.transformOptions)
            : value;
    }
Example #9
Source File: SocketResponseModel.ts    From viewer-components-react with MIT License 5 votes vote down vote up
constructor(response: any) {
    this.result = response.result || undefined;
    this.error = plainToInstance(SocketError, response.error as object) || undefined;
  }
Example #10
Source File: AuthService.ts    From viewer-components-react with MIT License 5 votes vote down vote up
public getIModelAccess$(requestSensemetricsAuthToken = false): Observable<AuthState> {
    return ConfigService.getRestApi$()
      .pipe(
        switchMap((restApi: string) => {
          return this.getITwinAccessToken$()
            .pipe(
              switchMap((accessToken: string | null) => {
                if (accessToken) {
                  let requestUrl = restApi + this.endpoints.iModelAccessRequest;
                  if (requestSensemetricsAuthToken) {
                    requestUrl += "?includeAccess=true";
                  }
                  return from(
                    axios.post(requestUrl, {
                      iModelId: IModelApp.viewManager.selectedView?.iModel.iModelId,
                      token: accessToken,
                    })
                  ).pipe(
                    tap({
                      error: (error: any) => {
                        LoggerService.warn("Error retrieving iModel access:", error.response || error);
                      },
                    }),
                    map((response: AxiosResponse<{associations: {[key: string]: any}[]}>) => {
                      if (response.data.associations && response.data.associations.length) {
                        LoggerService.log("Retrieved iModel access:", response.data);
                        return plainToInstance(AuthState, response.data.associations[0]);
                      } else {
                        LoggerService.warn("Received malformed iModel access data:", response.data);
                        return throwError(() => {});
                      }
                    })
                  ) as Observable<AuthState>;
                } else {
                  LoggerService.warn("Error loading iModel access: User access token not available");
                  return throwError(() => {});
                }
              })
            );
        })
      );
  }
Example #11
Source File: AlertService.ts    From viewer-components-react with MIT License 5 votes vote down vote up
private getAlert$(id: string): Observable<Alert> {
    return ApiService.sendRequest$(this.endpoints.getAlert + id)
      .pipe(
        tap((data: any) => LoggerService.log("Received alert:", data)),
        map((data: object) => plainToInstance(Alert, data))
      );
  }
Example #12
Source File: MetricService.ts    From viewer-components-react with MIT License 5 votes vote down vote up
// NOTE: although this method technically supports retrieval of metrics for multiple sensors,
  // it currently returns only the metrics for the first sensor, due to the complexity
  // of merging metric categories, metrics, units and metric params for a group of sensors
  public getMetrics$(sensorIds: string[], enableIPIMetricFilters = false): Observable<MetricCategory[]> {
    const cacheKey = `${sensorIds.join("-")}-${enableIPIMetricFilters.toString()}`;
    if (this.metricCache.sensors[cacheKey]) {
      return of(this.metricCache.sensors[cacheKey]);
    } else {
      const params: {[key: string]: string} = { categorized: "true" };
      if (enableIPIMetricFilters) {
        params.filters = "xy";
      }
      return ApiService.sendRequest$(
        this.endpoints.getMetrics,
        "POST",
        { params, data: {ids: sensorIds} }
      ).pipe(
        tap((data: any) => LoggerService.log("Received metrics:", data)),
        catchError(() => of([])),
        map((data: any) => {

          let firstSensorMetrics: MetricCategory[] = [];

          // Loop through all metrics and their units, cache them so we can
          // quickly retrieve their names (all this work for such a small thing)
          if (data.metricsBySensor) {
            _forEach(data.metricsBySensor, (rawCategories: any[]) => {
              const categories = plainToInstance(MetricCategory, rawCategories);
              if (!firstSensorMetrics.length) {
                firstSensorMetrics = categories;
              }
              _forEach(categories, (category: MetricCategory) => {
                _forEach(category.getMetrics(), (metric: Metric) => {
                  this.metricCache.metrics[metric.getId()] = metric;
                  _forEach(metric.getUnits(), (unit: Unit) => {
                    this.metricCache.units[unit.getId()] = unit;
                  });
                });
              });
            });
          }

          // Save metrics in cache so we don"t have to make this request again
          this.metricCache.sensors[cacheKey] = firstSensorMetrics;

          return firstSensorMetrics;
        })
      );
    }
  }