How to use class-transformer - 10 common examples

To help you get started, we’ve selected a few class-transformer 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 ZhiXiao-Lin / nestify / server / src / common / services / user.service.ts View on Github external
if (!!payload.isExport) {
            if (!payload.category) throw new BadRequestException('分类参数错误');

            const dataSource = await qb.getMany();

            // 执行导出逻辑
            // return await ExcelHelper.export(dataSource, Content.sheetsMap[payload.category], payload.fields.split(','));
        } else {
            qb.skip(payload.page * payload.pageSize);
            qb.take(payload.pageSize);
        }

        return await qb.getManyAndCount();
    }

    @TransformClassToPlain()
    async details(payload: any) {
        const qb = this.detailRepository.createQueryBuilder('t');

        qb.leftJoinAndSelect('t.user', 'user');

        if (!payload.page) {
            payload.page = 0;
        }

        if (!payload.pageSize) {
            payload.pageSize = 10;
        }

        qb.andWhere('user.id =:id', { id: payload.userId });

        if (!!payload.create_at) {
github rucken / cli / entity / src / apps / demo / migrations / 1533634559618-AddDemoTable.ts View on Github external
.getRepository(ContentType)
      .save(
        plainToClass(ContentType, { name: 'demo', title: 'Demo' })
      );
    const ctUser = await queryRunner.manager
      .getRepository(ContentType)
      .findOneOrFail({
        where: {
          name: 'user'
        }
      });
    // create permissions
    const readPermissions = await queryRunner.manager
      .getRepository(Permission)
      .save(
        plainToClass(Permission, [
          {
            title: 'Can read demo',
            name: 'read_demo',
            contentType: ctNewEntity
          },
          {
            title: 'Can read demos frame',
            name: 'read_demos-frame',
            contentType: ctUser
          },
          {
            title: 'Can read demos page',
            name: 'read_demos-page',
            contentType: ctUser
          }
        ])
github dilame / instagram-private-api / src / models / media.ts View on Github external
get webLink() {
    return `https://www.instagram.com/p/${this.code}/`;
  }

  // Backward compatibility
  @Expose()
  get account() {
    return this.user;
  }

  @Expose()
  get takenAt() {
    return this.taken_at * 1000;
  }

  @Expose()
  get images() {
    return this.image_versions2;
  }

  @Expose()
  get videos() {
    return this.video_versions;
  }
}
github rucken / core / libs / rucken / core / src / lib / models / group.ts View on Github external
createTitle: translate('Add new group'),
    viewTitle: translate('Group #{{id}}'),
    updateTitle: translate('Update group #{{id}}'),
    deleteTitle: translate('Delete group #{{id}}'),
    deleteMessage: translate('Do you really want to delete group?'),
    selectTitle: translate('Select group')
  };
  // need for deep update if local change in any place
  static nested = {
    permissions: Permission
  };
  id: number = undefined;
  @IsNotEmpty()
  name: string = undefined;
  title: string = undefined;
  @Type(serializeModel(Permission))
  permissions: Permission[] = [];
  get permissionsAsString() {
    if (this.permissions) {
      const permissionsLength = this.permissions.length;
      if (permissionsLength > 14) {
        return (
          this.permissions.filter((item, index) => index < 7).join(', ') +
          (permissionsLength > 7 ? `... +${permissionsLength - 7}` : '')
        );
      }
      return this.permissions.join(', ');
    } else {
      return '';
    }
  }
  toString() {
github ZhiXiao-Lin / nestify / server / src / common / services / content.service.ts View on Github external
if (!payload.category) throw new BadRequestException('分类参数错误');

            return await qb.getMany();
        } else {
            qb.skip(payload.page * payload.pageSize);
            qb.take(payload.pageSize);
        }

        const [list, count] = await qb.getManyAndCount();

        Promise.all(list.map(item => this.saveViewsFromCache(item.id)));

        return [list, count];
    }

    @TransformClassToPlain()
    async findOneById(id) {
        return await this.contentRepository.findOne({
            where: { id },
            relations: ['category']
        });
    }

    async saveViewsFromCache(id) {
        const currentTime = moment().format('YYYY-MM-DD HH:mm:ss');
        Logger.debug('currentTime', currentTime);

        // 文章最后访问时间
        const lastTime = await redis.hget('content_lastTime', `${id}`);
        Logger.debug('lastTime', lastTime);

        if (!!lastTime) {
github ZhiXiao-Lin / nestify / server / src / common / services / role.service.ts View on Github external
import { TransformClassToPlain } from 'class-transformer';
import { BaseService } from './base.service';
import { Role } from '../entities/role.entity';

@Injectable()
export class RoleService extends BaseService {
    constructor(@InjectRepository(Role) private readonly roleRepository: Repository) {
        super(roleRepository);
    }

    @TransformClassToPlain()
    async findOneAndRelations(id: string) {
        return await this.roleRepository.findOne({ where: { id }, relations: ['authorities'] });
    }

    @TransformClassToPlain()
    async query(payload: any) {
        const qb = this.roleRepository.createQueryBuilder('t');

        qb.leftJoinAndSelect('t.authorities', 'authorities');

        if (!!payload.keyword) {
            qb.andWhere(`t.name LIKE '%${payload.keyword}%'`);
        }

        if (!!payload.sort && !!payload.order) {
            qb.addOrderBy(`t.${payload.sort}`, payload.order);
        } else {
            // 默认排序规则
            qb.addOrderBy('t.sort', 'DESC');
        }
github ZhiXiao-Lin / nestify / server / src / common / services / user.service.ts View on Github external
return await this.jwtService.sign(_.toPlainObject(user));
    }

    async changePassword(id, dto) {
        const user = await this.userRepository.findOne({ where: { id }, relations: ['role'] });

        if (!(await bcrypt.compare(dto.oldPassword, user.password)))
            throw new BadRequestException('旧密码错误');

        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(dto.password, salt);

        return await this.userRepository.save(user);
    }

    @TransformClassToPlain()
    @Transaction()
    async save(
        payload: any,
        @TransactionRepository(User) userRepos?: Repository,
        @TransactionRepository(Detail) detailRepos?: Repository,
        @TransactionRepository(Role) rowRepos?: Repository
    ) {
        const user = User.create(payload) as User;

        if (!user.role) {
            // 添加默认角色
            const role = await rowRepos.findOne({ where: { token: 'user' } });
            user.role = role;
        }
github tokilabs / plow / src / eventSourcing / eventStoreProviders / gesEventStore.ts View on Github external
private convertToEnvelope(event: EventStore.ResolvedEvent): EventEnvelope {
    const e = event.event;

    const metadata = JSON.parse(e.metadata.toString());
    const eventClass = requireByFQN(e.eventType);

    return new EventEnvelope(
      new Guid(e.eventId),
      metadata.aggregateType, // aggregateType
      metadata.aggregateId, // aggregateId
      e.eventNumber, // version
      deserialize(eventClass, e.data.toString()), // eventData
      e.eventType, // eventType
      metadata,
      new Date(e.createdEpoch) // created
    );
  }