How to use @nestjs/common - 10 common examples

To help you get started, weโ€™ve selected a few @nestjs/common 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 Jarvie8176 / casbin-example / src / service / authz / authz.service.ts View on Github external
private validation(query: AuthzQuery): void {
    // must call init() before the module being used
    if (!this.inited) throw new InvalidState("must call init() first");

    // query.data must not contain reserved keywords
    const reservedKeywordMatch = _.intersection(_.keys(query.data), AuthorizationService.ReservedKeywords);
    if (!_.isEmpty(reservedKeywordMatch)) {
      throw new UnauthorizedException(`query.input contained reserved keyword(s): ${reservedKeywordMatch.join(", ")}`);
    }
  }
github vendure-ecommerce / vendure / packages / core / src / service / helpers / asset-updater / asset-updater.ts View on Github external
import { idsAreEqual } from '../../../common/utils';
import { Asset, VendureEntity } from '../../../entity';
import { AssetService } from '../../services/asset.service';

export interface EntityWithAssets extends VendureEntity {
    featuredAsset: Asset;
    assets: Asset[];
}

export interface AssetInput {
    featuredAssetId?: string | null;
    assetIds?: string[] | null;
}

@Injectable()
export class AssetUpdater {
    constructor(@InjectConnection() private connection: Connection, private assetService: AssetService) {}

    /**
     * Updates the assets / featuredAsset of an entity, ensuring that only valid assetIds are used.
     */
    async updateEntityAssets(entity: T, input: AssetInput) {
        if (input.assetIds || input.featuredAssetId) {
            if (input.assetIds) {
                const assets = await this.assetService.findByIds(input.assetIds);
                entity.assets = assets;
                const featuredAssetId = input.featuredAssetId;
                if (featuredAssetId) {
                    // If the featuredAsset is also being set, we save the additional
                    // DB query since we already have that asset from the findByIds query.
                    const featuredAsset = assets.find(a => idsAreEqual(a.id, featuredAssetId));
github bojidaryovchev / nest-angular / src / server / modules / auth / auth.module.ts View on Github external
import { authenticate } from 'passport';

// Strategies
import { LocalStrategy } from './passport/local.strategy';
import { JwtStrategy } from './passport/jwt.strategy';
import { FacebookStrategy } from './passport/facebook.strategy';
import { TwitterStrategy } from './passport/twitter.strategy';
import { GoogleStrategy } from './passport/google-plus.strategy';

import { UserModule } from '../user/user.module';
import { authProviders } from './auth.providers';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { bodyValidatorMiddleware } from './middlewares/body-validator.middleware';

@Module({
  imports: [UserModule],
  providers: [
    ...authProviders,
    AuthService,
    LocalStrategy,
    JwtStrategy,
    FacebookStrategy,
    TwitterStrategy,
    GoogleStrategy
  ],
  controllers: [AuthController]
})
export class AuthModule implements NestModule {
  public configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(
github Coding-Coach / find-a-mentor-api / src / modules / lists / favorites.controller.ts View on Github external
import { List } from './interfaces/list.interface';
import { UsersService } from '../common/users.service';
import { ListsService } from './lists.service';
import { ListDto } from './dto/list.dto';

@ApiUseTags('/users/:userid/favorites')
@ApiBearerAuth()
@Controller('users/:userid/favorites')
export class FavoritesController {
  constructor(
    private readonly usersService: UsersService,
    private readonly listsService: ListsService,
  ) {}

  @ApiOperation({ title: 'Returns the favorite list for the given user' })
  @Get()
  async list(@Req() request: Request, @Param('userid') userId: string) {
    const current: User = await this.usersService.findByAuth0Id(
      request.user.auth0Id,
    );
    const user: User = await this.usersService.findById(userId);

    // Make sure user exist
    if (!user) {
      throw new BadRequestException('User not found');
    }

    // Only admins or current user can get the favorites
    if (!current._id.equals(user._id) && !current.roles.includes(Role.ADMIN)) {
      throw new UnauthorizedException(
        'Not authorized to perform this operation',
      );
github joe307bad / points / API.Points / src / upload / upload.controller.ts View on Github external
import { Controller, UseGuards, Get, Post, Body, UseInterceptors, UploadedFile, Res } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { AuthGuard } from '@nestjs/passport';
import { UploadDto, IUploadService } from '@points/shared';
const gm = require('gm').subClass({ imageMagick: true });
import * as sizeOf from 'image-size';

import { ApiAction, ApiPermission, PermissionGaurd, HasPermission } from '../core/acl';
import { UploadService } from './upload.service';
import { UploadFileSettings, uploadDir } from '../app.settings';
import {OnlyApprovedUsers} from '../auth/guards/approved.guard';

const resource = 'upload';
export const to = (action: ApiAction) => new ApiPermission(action, resource, 'userId', 'objectId');

@Controller(resource)
@UseGuards(AuthGuard('jwt'), PermissionGaurd, OnlyApprovedUsers)
export class UploadController implements IUploadService {
    constructor(private readonly upload: UploadService) { }

    @Post()
    @HasPermission(to('create'))
    // TODO restrict to only images
    @UseInterceptors(FileInterceptor('photo', UploadFileSettings))
    async create(@Body() upload: UploadDto, @UploadedFile() photo, @Res() res): Promise {
        if (!!photo) {
            upload.photo = photo.filename;
            this.generateThumbnail(upload.photo);
            this.generateMedium(upload.photo);
            return res.send(await this.upload.create(upload).catch(err => err));
        } else {
            return res.status(404).send('Not found');
github xmlking / ngx-starter-kit / apps / api / src / app / user / email / email.controller.ts View on Github external
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { ApiOAuth2, ApiTags } from '@nestjs/swagger';
import { CurrentUser } from '../../auth/decorators';
import { EmailService } from '../../email';
import { User } from '../user.entity';
import { EmailDto } from './dto/email.dto';

@ApiOAuth2(['read'])
@ApiTags('Email', 'User')
@Controller('email')
export class EmailController {
  constructor(private readonly emailService: EmailService) {}

  // @ApiExcludeEndpoint()
  @Post()
  @HttpCode(HttpStatus.CREATED)
  async sendEmail(@Body() email: EmailDto, @CurrentUser() user: User): Promise {
    return this.emailService.sendMail({
      to: user.email,
      subject: email.title,
      template: 'welcome', // The `.pug` extension is appended automatically.
      context: {
        // Data to be sent to PugJS template files.
        title: email.title,
        comments: email.comments,
        name: email.name,
      },
    });
  }
}
github alexitaylor / angular-graphql-nestjs-postgres-starter-kit / server / project / src / messages / messages.resolvers.ts View on Github external
Query,
  Resolver,
  Subscription,
  Context,
} from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';
import { MessagesService } from './messages.service';
import { MessagesDto, MessageConnection } from './dto/messages.dto';
import { AuthGuard } from '../auth/guards/auth.guard';
import { Roles } from '../decorators/roles.decorators';
import { RolesGuard } from '../auth/guards/roles.guard';

const pubSub = new PubSub();

@Resolver('Message')
@UseGuards(new AuthGuard(), RolesGuard)
export class MessagesResolvers {
  constructor(private readonly messagesService: MessagesService) {}

  // TODO pagination cursor instead of page???
  @Query('messages')
  @Roles('ADMIN', 'USER')
  async getMessages(
    @Args('page') page: number,
    @Args('limit') limit: number,
    @Args('newest') newest: boolean,
  ): Promise {
    return await this.messagesService.findAll(page, limit, newest);
  }

  @Query('message')
  @Roles('ADMIN', 'USER')
github Coding-Coach / find-a-mentor-api / src / modules / lists / lists.controller.ts View on Github external
async updateList(
    @Req() request: Request,
    @Param('userid') userId: string,
    @Param('listid') listId: string,
    @Body() data: ListDto,
  ) {
    const current: User = await this.usersService.findByAuth0Id(
      request.user.auth0Id,
    );
    const user: User = await this.usersService.findById(userId);

    // check if user exists
    if (!user) {
      throw new BadRequestException('User not found');
    }

    // only admins and current user can update lists
    if (!current._id.equals(user._id) && !current.roles.includes(Role.ADMIN)) {
      throw new UnauthorizedException(
        'Not authorized to perform this operation',
      );
    }

    const list: List[] = await this.listsService.findByUserId({
      userId,
      listId,
      isFavorite: false,
    });

    // check if list exists
github nestjs / nest / packages / microservices / client / client-kafka.ts View on Github external
protected getReplyTopicPartition(topic: string): string {
    const topicAssignments = this.consumerAssignments[topic];
    if (isUndefined(topicAssignments)) {
      throw new InvalidKafkaClientTopicException(topic);
    }

    // if the current member isn't listening to
    // any partitions on the topic then throw an error.
    if (isUndefined(topicAssignments[0])) {
      throw new InvalidKafkaClientTopicPartitionException(topic);
    }
    return topicAssignments[0].toString();
  }
github juicycleff / ultimate-backend / apps / service-notification / src / email / queue / auth.queue.ts View on Github external
import {
  Processor,
  Process,
  OnQueueActive,
  OnQueueEvent,
  BullQueueEvents,
} from 'nest-bull';
import { Job } from 'bull';
import { Logger } from '@nestjs/common';
import { UserEntity } from '@graphqlcqrs/repository';
import { EmailService } from '../email.service';

@Processor({ name: 'auth_queue' })
export class AuthQueue {
  private readonly logger = new Logger(this.constructor.name);
  constructor(
    private readonly service: EmailService,
    // private readonly configService: ConfigService,
  ) {}

  @Process({ name: 'UserRegistered' })
  async processUserRegister(job: Job) {
    if (job.data) { return; }

    const user = job.data;
    const userEmail = user.emails.reduce(previousValue => previousValue.primary === true && previousValue);

    await this.service.sendEmail({
      to: userEmail.address,
      from: 'noreply@demo.com',
      subject: 'Thank for registering',