@nestjs/common#UseFilters TypeScript Examples

The following examples show how to use @nestjs/common#UseFilters. 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: app.gateway.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
/**
 * The class implements working with sockets
 */
@UseFilters(WsExceptionsFilter)
@WebSocketGateway(3001)
export default class AppGateway {
  /**
   * Returns you Hello world!
   * @returns {string} Hello, World!
   */
  @UseGuards(JwtWSAccessGuard)
  @SubscribeMessage('event')
  handleEvent() {
    return 'Hello, World!';
  }
}
Example #2
Source File: user-points.jobs.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@MessagePattern(GraphileWorkerPattern.REFRESH_USER_POINTS)
  @UseFilters(new GraphileWorkerException())
  async refreshUserPoints({
    userId,
  }: RefreshUserPointsOptions): Promise<GraphileWorkerHandlerResponse> {
    const user = await this.usersService.find(userId);
    if (!user) {
      this.loggerService.error(`No user found for '${userId}'`, '');
      return { requeue: false };
    }

    const options = await this.eventsService.getUpsertPointsOptions(user);
    await this.userPointsService.upsert(options);
    return { requeue: false };
  }
Example #3
Source File: user-points.jobs.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@MessagePattern(GraphileWorkerPattern.REFRESH_USERS_POINTS)
  @UseFilters(new GraphileWorkerException())
  async refreshUsersPoints(): Promise<GraphileWorkerHandlerResponse> {
    for await (const user of this.usersGenerator()) {
      await this.graphileWorkerService.addJob<RefreshUserPointsOptions>(
        GraphileWorkerPattern.REFRESH_USER_POINTS,
        { userId: user.id },
      );
    }
    return { requeue: false };
  }
Example #4
Source File: events.jobs.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@MessagePattern(GraphileWorkerPattern.UPDATE_LATEST_POINTS)
  @UseFilters(new GraphileWorkerException())
  async updateLatestPoints({
    userId,
    type,
  }: {
    userId: number;
    type: EventType;
  }): Promise<void> {
    await this.eventsService.updateLatestPoints(userId, type);
  }
Example #5
Source File: events.jobs.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@MessagePattern(GraphileWorkerPattern.DELETE_BLOCK_MINED_EVENT)
  @UseFilters(new GraphileWorkerException())
  async deleteBlockMinedEvent({
    block_id: blockId,
  }: DeleteBlockMinedEventOptions): Promise<GraphileWorkerHandlerResponse> {
    const block = await this.blocksService.find(blockId);
    if (!block) {
      this.loggerService.error(`No block found for '${blockId}'`, '');
      return { requeue: false };
    }

    await this.eventsService.deleteBlockMined(block);
    return { requeue: false };
  }
Example #6
Source File: events.jobs.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@MessagePattern(GraphileWorkerPattern.UPSERT_BLOCK_MINED_EVENT)
  @UseFilters(new GraphileWorkerException())
  async upsertBlockMinedEvent({
    block_id: blockId,
    user_id: userId,
  }: UpsertBlockMinedEventOptions): Promise<GraphileWorkerHandlerResponse> {
    const user = await this.usersService.find(userId);
    if (!user) {
      this.loggerService.error(`No user found for '${userId}'`, '');
      return { requeue: false };
    }

    const block = await this.blocksService.find(blockId);
    if (!block) {
      this.loggerService.error(`No block found for '${blockId}'`, '');
      return { requeue: false };
    }

    await this.eventsService.upsertBlockMined(block, user);
    return { requeue: false };
  }
Example #7
Source File: blocks-daily.jobs.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@MessagePattern(GraphileWorkerPattern.SYNC_BLOCKS_DAILY)
  @UseFilters(new GraphileWorkerException())
  async sync({
    date,
  }: SyncBlocksDailyOptions): Promise<GraphileWorkerHandlerResponse> {
    date = new Date(date);
    const head = await this.blocksService.head();
    const diffInMs = head.timestamp.getTime() - date.getTime();
    const diffInDays = diffInMs / MS_PER_DAY;
    // The heaviest head should be at least 24 hours after `date` to run a backfill for a day
    if (diffInDays < 1) {
      return { requeue: false };
    }

    await this.blocksDailyLoader.loadDateMetrics(date);

    const nextDate = getNextDate(date);
    await this.graphileWorkerService.addJob<SyncBlocksDailyOptions>(
      GraphileWorkerPattern.SYNC_BLOCKS_DAILY,
      { date: nextDate },
    );

    return { requeue: false };
  }
Example #8
Source File: auth.controller.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@UseInterceptors(MorganInterceptor('combined'))
  @UseFilters(GithubAuthExceptionFilter)
  @Get('/github/callback')
  @UseGuards(AuthGuard('github'))
  async githubCallback(@Req() request: Request, @Res() response: Response) {
    const user: AuthUser = request.user as AuthUser;
    this.logger.log({
      level: 'info',
      message: `receive login callback from github account_id=${user.account.id}`
    });
    const token = await this.authService.prepareToken(user);
    response.redirect(301, `${this.host}?token=${token}`);
  }
Example #9
Source File: deposits.jobs.controller.ts    From ironfish-api with Mozilla Public License 2.0 5 votes vote down vote up
@MessagePattern(GraphileWorkerPattern.UPSERT_DEPOSIT)
  @UseFilters(new GraphileWorkerException())
  async upsert(
    options: UpsertDepositsOperationDto,
  ): Promise<GraphileWorkerHandlerResponse> {
    await this.depositsUpsertService.upsert(options);
    return { requeue: false };
  }
Example #10
Source File: chat.controller.ts    From Phantom with MIT License 5 votes vote down vote up
@UseFilters(HttpExceptionFilter)
@Controller()
export class ChatController {
  constructor(private ChatService: ChatService) {}

  @UseGuards(AuthGuard('jwt'))
  @Get('/getMessagesSent/:recieverIds/:senderId')
  async getMessagesSent(
    @Param('recieverIds') recieverIds: string,
    @Param('senderId') senderId: string,
  ) {
    let ids = recieverIds.split(',');
    let messages = await this.ChatService.getMessage(ids, senderId);
    if (messages) return messages;
    throw new NotFoundException('there is no messages');
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/getChats/:userId')
  async getChats(@Param('userId') userId) {
    let messages = await this.ChatService.getChats(userId);
    if (messages) return messages;
    throw new NotFoundException();
  }
  @UseGuards(AuthGuard('jwt'))
  @Post('/seen')
  async seenDeliver(
    @Body('senderId') senderId: string,
    @Body('recieverId') recieverId: string,
    @Body('time') time: string,
  ) {
    let messages = await this.ChatService.seenMessage(
      senderId,
      recieverId,
      time,
    );
    if (messages) return messages;
    throw new NotFoundException();
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('/sentMessage')
  async sentMessage(
    @Body('senderId') senderId: string,
    @Body('recieverId') recieverId: [string],
    @Body('message') message: string,
    @Body('name') name: string,
  ) {
    let messages = await this.ChatService.sendMessage(
      senderId,
      recieverId,
      message,
    );
    if (messages) return messages;
    throw new NotFoundException();
  }
}
Example #11
Source File: images.controller.ts    From Phantom with MIT License 5 votes vote down vote up
@UseFilters(HttpExceptionFilter)
@Controller()
export class ImagesController {
  constructor(private ImagesService: ImagesService) {}

  @Post('/me/uploadImage')
  @ApiConsumes('multipart/form-data')
  @UseInterceptors(FilesInterceptor('file'))
  async uploadImage(@UploadedFiles() files, @Request() req) {
    return await this.ImagesService.uploadFile(
      files[0].originalname,
      files[0].mimetype,
      files[0].buffer,
    );
  }

  @Get('/image/:id')
  async getImage(@Param('id') id: string, @Res() response, @Request() req) {
    if (!id || id == ' ' || id == '' || id == 'none' || id == 'null') {
      var filePath = './src/static/default.jpg';
      var resolvedPath = await path.resolve(filePath);
      return response.sendFile(resolvedPath);
    }
    await this.ImagesService.drive.files.get(
      { fileId: id, alt: 'media' },
      { responseType: 'stream' },
      function(err, res) {
        if (err) {
          console.log(err);
          var filePath = './src/static/default.jpg';
          var resolvedPath = path.resolve(filePath);
          return response.sendFile(resolvedPath);
        }
        res.data
          .on('end', () => {})
          .on('error', err => {
            var filePath = './src/static/default.jpg';
            var resolvedPath = path.resolve(filePath);
            return response.sendFile(resolvedPath);
          })
          .pipe(response);
      },
    );
  }
}
Example #12
Source File: search.controller.ts    From Phantom with MIT License 5 votes vote down vote up
@UseFilters(HttpExceptionFilter)
@Controller('search')
export class SearchController {
  constructor(private SearchService: SearchService) {}
  @UseGuards(AuthGuard('jwt'))
  @Get('/allPins')
  async getAllPins(
    @Request() req,
    @Query('name') name: string,
    @Query('recentSearch') recentSearch: Boolean,
    @Query('limit') limit: number,
    @Query('offset') offset: number,
  ) {
    let userId = req.user._id;
    if (recentSearch) await this.SearchService.addToRecentSearch(userId, name);
    let pins = await this.SearchService.getAllPins(name, limit, offset);
    if (pins) return pins;
    return new NotFoundException();
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/myPins')
  async getMyPins(
    @Request() req,
    @Query('name') name: string,
    @Query('recentSearch') recentSearch: Boolean,
    @Query('limit') limit: number,
    @Query('offset') offset: number,
  ) {
    let userId = req.user._id;
    if (recentSearch) await this.SearchService.addToRecentSearch(userId, name);
    let pins = await this.SearchService.getMyPins(name, userId, limit, offset);
    if (pins) return pins;
    return new NotFoundException();
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/people')
  async getPeople(
    @Request() req,
    @Query('name') name: string,
    @Query('recentSearch') recentSearch: Boolean,
    @Query('limit') limit: number,
    @Query('offset') offset: number,
  ) {
    let userId = req.user._id;
    if (recentSearch) await this.SearchService.addToRecentSearch(userId, name);
    let users = await this.SearchService.getPeople(name, limit, offset);
    if (users) return users;
    return new NotFoundException();
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/board')
  async getBoards(
    @Request() req,
    @Query('recentSearch') recentSearch: Boolean,
    @Query('name') name: string,
    @Query('limit') limit: number,
    @Query('offset') offset: number,
  ) {
    let userId = req.user._id;
    if (recentSearch) await this.SearchService.addToRecentSearch(userId, name);
    let boards = await this.SearchService.getBoards(name, limit, offset);
    if (boards) return boards;
    return new NotFoundException();
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/recentSearch')
  async getRecentSearch(@Request() req) {
    let userId = req.user._id;
    let recentSearch = await this.SearchService.getRecentSearch(userId);
    if (recentSearch) return recentSearch;
    return new NotFoundException();
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/getKeys')
  async getKeys(@Request() req, @Query('name') name) {
    let recentSearch = await this.SearchService.getKeys(name);
    if (recentSearch) return recentSearch;
    return new NotFoundException();
  }
}
Example #13
Source File: git.resolver.ts    From amplication with Apache License 2.0 4 votes vote down vote up
@UseFilters(GqlResolverExceptionsFilter)
@UseGuards(GqlAuthGuard)
export class GitResolver {
  constructor(private readonly gitService: GitProviderService) {}
  @Mutation(() => App)
  @AuthorizeContext(
    AuthorizableResourceParameter.GitOrganizationId,
    'data.gitOrganizationId'
  )
  async createGitRepository(
    @Args() args: CreateGitRepositoryArgs
  ): Promise<App> {
    return this.gitService.createGitRepository(args.data);
  }

  @Query(() => GitOrganization)
  @AuthorizeContext(AuthorizableResourceParameter.GitOrganizationId, 'where.id')
  async gitOrganization(@Args() args: FindOneArgs): Promise<GitOrganization> {
    return this.gitService.getGitOrganization(args);
  }

  @Mutation(() => App)
  @AuthorizeContext(
    AuthorizableResourceParameter.GitOrganizationId,
    'data.gitOrganizationId'
  )
  async connectAppGitRepository(
    @Args() args: ConnectGitRepositoryArgs
  ): Promise<App> {
    return await this.gitService.connectAppGitRepository(args.data);
  }

  @Mutation(() => GitOrganization)
  @InjectContextValue(
    InjectableResourceParameter.WorkspaceId,
    'data.workspaceId'
  )
  async createOrganization(
    @Args() args: CreateGitOrganizationArgs
  ): Promise<GitOrganization> {
    return await this.gitService.createGitOrganization(args);
  }

  @Mutation(() => App)
  @AuthorizeContext(
    AuthorizableResourceParameter.GitRepositoryId,
    'gitRepositoryId'
  )
  async deleteGitRepository(
    @Args() args: DeleteGitRepositoryArgs
  ): Promise<App> {
    return this.gitService.deleteGitRepository(args);
  }

  @Mutation(() => Boolean)
  @AuthorizeContext(
    AuthorizableResourceParameter.GitOrganizationId,
    'gitOrganizationId'
  )
  async deleteGitOrganization(
    @Args() args: DeleteGitOrganizationArgs
  ): Promise<boolean> {
    return this.gitService.deleteGitOrganization(args);
  }

  @Mutation(() => AuthorizeAppWithGitResult)
  @InjectContextValue(
    InjectableResourceParameter.WorkspaceId,
    'data.workspaceId'
  )
  async getGitAppInstallationUrl(
    @Args() args: GetGitInstallationUrlArgs
  ): Promise<AuthorizeAppWithGitResult> {
    return {
      url: await this.gitService.getGitInstallationUrl(args)
    };
  }

  @Query(() => [RemoteGitRepository])
  @AuthorizeContext(
    AuthorizableResourceParameter.GitOrganizationId,
    'where.gitOrganizationId'
  )
  async remoteGitRepositories(
    @Args() args: RemoteGitRepositoriesFindManyArgs
  ): Promise<RemoteGitRepository[]> {
    return this.gitService.getReposOfOrganization(args.where);
  }

  @Query(() => [GitOrganization])
  @InjectContextValue(
    InjectableResourceParameter.WorkspaceId,
    'where.workspaceId'
  )
  async gitOrganizations(
    @Args() args: GitOrganizationFindManyArgs
  ): Promise<GitOrganization[]> {
    return this.gitService.getGitOrganizations(args);
  }
}
Example #14
Source File: user.resolver.ts    From nestjs-mercurius with MIT License 4 votes vote down vote up
@UseFilters(ForbiddenExceptionFilter)
@Resolver(() => UserType)
export class UserResolver {
  constructor(
    private readonly userService: UserService,
    private readonly postService: PostService,
  ) {}

  @Query(() => [UserType], {
    complexity: (options) => options.childComplexity + 5,
  })
  users() {
    return this.userService.users();
  }

  @Query(() => UserType, { nullable: true })
  user(@Args({ name: 'id', type: () => ID }, ParseIntPipe) id: number) {
    return this.userService.find(id);
  }

  @Mutation(() => UserType)
  createUser(
    @Args({ name: 'input', type: () => CreateUserInput }) data: CreateUserInput,
    @Context() ctx: MercuriusContext,
  ) {
    const user = this.userService.create(data);

    return user;
  }

  @ResolveField(() => Int, { complexity: 5 })
  async age(
    @Parent() user: UserType,
    @Context('headers') headers: Record<string, any>,
  ) {
    return calculateAge(user.birthDay);
  }

  @ResolveLoader(() => String, {
    nullable: true,
    complexity: (options) => {
      return 5;
    },
    middleware: [
      async (ctx, next) => {
        const results = await next();
        return results.map((res) => res || 'Missing');
      },
    ],
    opts: {
      cache: false,
    },
  })
  async fullName(
    @Args({ type: () => FullNameArgs }) args: FullNameArgs[],
    @Parent() p: LoaderQuery<UserType>[],
    @Context() ctx: Record<string, any>,
    @Header('authorization') auth?: string,
  ) {
    return p.map(({ obj }) => {
      if (obj.name && obj.lastName) {
        return `${obj.name} ${obj.lastName}`;
      }
      return obj.name || obj.lastName;
    });
  }

  // @UseGuards(AuthGuard)
  @UseInterceptors(LogInterceptor)
  @ResolveLoader(() => [PostType])
  async posts(@Parent() queries: LoaderQuery<UserType>[]) {
    return this.postService.userPostLoader(queries.map((q) => q.obj.id));
  }

  @UseInterceptors(LogInterceptor)
  @Subscription(() => UserType)
  async userAdded(@Context() ctx: MercuriusContext) {
    return ctx.pubsub.subscribe('USER_ADDED');
  }

  @Subscription(() => String, {
    resolve: (payload) => {
      return payload.userAdded.id;
    },
  })
  async userAddedId(@Context() ctx: MercuriusContext) {
    return ctx.pubsub.subscribe('USER_ADDED');
  }

  @Subscription(() => UserType, {
    filter: (payload, variables: { id: string }) => {
      return payload.userAdded.id === variables.id;
    },
    resolve: (payload) => {
      return payload.userAdded;
    },
  })
  async specificUserAdded(
    @Args({ name: 'id', type: () => ID }) id: string,
    @Context() ctx: MercuriusContext,
  ) {
    return toAsyncIterator(ctx.pubsub.subscribe('USER_ADDED'));
  }
}
Example #15
Source File: auth.controller.ts    From Phantom with MIT License 4 votes vote down vote up
@UseFilters(HttpExceptionFilter)
@Controller()
export class AuthController {
  constructor(
    private userService: UserService,
    private authService: AuthService,
    private email: Email,
  ) {}
  @Get('google')
  @UseGuards(AuthGuard('google'))
  async googleAuth(@Req() req) {}

  @Get('google/redirect')
  @UseGuards(AuthGuard('google'))
  async googleAuthRedirect(@Req() req, @Res() res) {
    const data = await this.authService.googleLogin(req);
    if (data) {
      res.redirect(
        process.env.FRONT_BASE_URL +
          '/aouth/google?token=' +
          data.token +
          '&type=' +
          data.type,
      );
    } else {
      throw new NotFoundException();
    }
  }
  @Post('/login')
  async login(@Body() userDTO: LoginDto) {
    const user = await this.userService.findByLogin(userDTO);
    if (!user) throw new Error('topic not found');
    const payload: Payload = {
      _id: user._id,
    };
    const token = await this.authService.signPayload(payload);
    return { profileImage: user.profileImage, token };
  }

  @Post('/sign_up')
  async sign_up(@Body() userDTO: RegisterDto) {
    const user = await this.userService.checkCreateData(userDTO);
    const token = await this.authService.signPayload(userDTO);
    await this.email.sendEmail(
      userDTO.email,
      token,
      'confirm',
      userDTO.firstName,
    );
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('/sign_up/confirm')
  async confirm(@Request() req) {
    const user = await this.userService.createUser(req.user);
    const payload: Payload = {
      _id: user._id,
    };
    const token = await this.authService.signPayload(payload);
    return { profileImage: user.profileImage, token };
  }

  @Get('/checkEmail')
  async checkEmail(@Query('email') email: string) {
    const user = await this.userService.checkMAilExistAndFormat(email);
    if (user)
      throw new HttpException('this user is exists', HttpStatus.FORBIDDEN);
  }
  @Post('/forget-password')
  async forgetPassword(@Body() body) {
    const user = await this.userService.checkMAilExistAndFormat(body.email);
    if (!user)
      throw new HttpException('not user by this email', HttpStatus.FORBIDDEN);
    const payload: Payload = {
      _id: user._id,
      email: user.email,
    };
    const token = await this.authService.signPayload(payload);
    await this.email.sendEmail(
      user.email,
      token,
      'forget Password',
      user.firstName,
    );
  }

  @UseGuards(AuthGuard('jwt'))
  @Delete('/me/delete')
  async deleteMe(@Request() req) {
    const user = await this.userService.getUserById(req.user._id);
    await this.userService.deleteUser(req.user._id);
    await this.email.sendEmail(
      user.email,
      null,
      'Delete account',
      user.firstName,
    );
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me')
  async me(@Request() req) {
    const user = await this.userService.getUserById(req.user._id);
    user.password = null;
    return { user };
  }
}
Example #16
Source File: board.controller.ts    From Phantom with MIT License 4 votes vote down vote up
@UseFilters(HttpExceptionFilter)
@Controller()
export class BoardController {
  constructor(private BoardService: BoardService) {}

  @UseGuards(AuthGuard('jwt'))
  @Post('/me/boards')
  async createBoard(
    @Request() req,
    @Body('name') name: string,
    @Body('startDate') startDate: string,
    @Body('endDate') endDate: string,
    @Body('status') status: string,
  ) {
    let userId = req.user._id;
    let createdBoard = await this.BoardService.createBoard(
      name,
      startDate,
      endDate,
      userId,
    );
    if (createdBoard) {
      return createdBoard;
    } else {
      throw new NotAcceptableException({ message: 'board not created' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me/boards')
  async getCurrentUserBoards(@Request() req) {
    let userId = req.user._id;
    req.setTimeout(0);
    let boards = await this.BoardService.getCurrentUserBoards(userId);
    if (boards && boards.length != 0) {
      return boards;
    } else {
      throw new NotFoundException({ message: 'no boards' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/users/:id/boards')
  async getSomeUserBoards(@Request() req, @Param('id') id: string) {
    let userId = req.user._id;
    let boards = await this.BoardService.getSomeUserBoards(userId, id);
    if (boards && boards.length != 0) {
      return boards;
    } else {
      throw new NotFoundException({ message: 'no boards' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/boards/state/:id')
  async isBoardPublic(@Param('id') id: string) {
    let state = await this.BoardService.isPublicBoard(id);
    return state;
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/boards/sortAZ')
  async sortBoardsAtoZ(@Request() req) {
    let userId = req.user._id;
    let boards = await this.BoardService.sortBoardsAtoZ(userId);
    if (boards) {
      return boards;
    } else {
      throw new NotFoundException({ message: 'no boards' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Put('/me/boards/sortDate')
  async sortBoardsDate(@Request() req) {
    let userId = req.user._id;
    let boards = await this.BoardService.sortBoardsDate(userId);
    if (boards) {
      return boards;
    } else {
      throw new NotFoundException({ message: 'no boards' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/boards/reorderBoards')
  async reorderBoards(
    @Request() req,
    @Query('startIndex') startIndex: number,
    @Query('positionIndex') positionIndex: number,
  ) {
    let userId = req.user._id;
    let boards = await this.BoardService.reorderBoards(
      userId,
      startIndex,
      positionIndex,
    );
    if (boards) {
      return boards;
    } else {
      throw new NotFoundException({ message: 'no boards' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/boards/edit/:boardId')
  async editBoard(
    @Request() req,
    @Param('boardId') boardId: string,
    @Body() editBoardDto: EditBoardDto,
  ) {
    let userId = req.user._id;
    let board = await this.BoardService.editBoard(
      boardId,
      userId,
      editBoardDto,
    );
    if (board) {
      return board;
    } else {
      throw new NotAcceptableException("board couldn't be updated");
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/boards/:boardId/collaboratores')
  async getCollaboratoresPermissions(
    @Request() req,
    @Param('boardId') boardId: string,
  ) {
    let userId = req.user._id;
    let collaboratores = await this.BoardService.getCollaboratoresPermissions(
      userId,
      boardId,
    );
    if (collaboratores) {
      return collaboratores;
    } else {
      throw new NotAcceptableException('collaboratores not found');
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Put('/me/boards/:boardId/collaboratores')
  async editCollaboratoresPermissions(
    @Request() req,
    @Param('boardId') boardId: string,
    @Body() editCollaboratoresPermissionsDto: EditCollaboratoresPermissionsDto,
  ) {
    let userId = req.user._id;
    let collaborator = await this.BoardService.editCollaboratoresPermissions(
      userId,
      boardId,
      editCollaboratoresPermissionsDto,
    );
    if (collaborator) {
      return collaborator;
    } else {
      throw new NotAcceptableException('collaborator couldnt be edited');
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Delete('/me/boards/:boardId/collaboratores')
  async deleteCollaborator(
    @Request() req,
    @Param('boardId') boardId: string,
    @Body('collaboratorId') collaboratorId: string,
  ) {
    let userId = req.user._id;
    let isdeleted = await this.BoardService.deleteCollaborator(
      userId,
      boardId,
      collaboratorId,
    );
    if (isdeleted) {
      return { success: 'collaborator has been deleted' };
    } else {
      throw new NotAcceptableException('collaborator couldnt be deleted');
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Delete('/me/boards/:boardId')
  async deleteBoard(@Request() req, @Param('boardId') boardId: string) {
    let userId = req.user._id;
    let deletedBoard = await this.BoardService.deleteBoard(userId, boardId);
    if (deletedBoard) {
      return { success: 'Board is deleted succissfully' };
    } else {
      throw new NotAcceptableException({ message: 'Board is not deleated' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Post('/me/boards/:boardId/section')
  async createSection(
    @Request() req,
    @Param('boardId') boardId: string,
    @Body('sectionName') sectionName: string,
  ) {
    let userId = req.user._id;
    let createSection = await this.BoardService.createSection(
      boardId,
      sectionName,
      userId,
    );
    if (createSection) {
      return createSection;
    } else {
      throw new NotAcceptableException({ message: 'Section is not created' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Delete('/me/boards/:boardId/section/:sectionId')
  async deleteSection(
    @Request() req,
    @Param('boardId') boardId: string,
    @Param('sectionId') sectionId: string,
  ) {
    let userId = req.user._id;
    let deleteSection = await this.BoardService.deleteSection(
      boardId,
      sectionId,
      userId,
    );
    if (deleteSection) {
      return { success: 'section deleted succissfully' };
    } else {
      throw new NotAcceptableException({ message: 'Section is not deleated' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Put('/me/boards/merge')
  async mergeBoards(
    @Request() req,
    @Body('originalBoardId') originalBoardId: string,
    @Body('mergedBoardId') mergedBoardId: string,
  ) {
    let userId = req.user._id;
    let board = await this.BoardService.merge(
      originalBoardId,
      mergedBoardId,
      userId,
    );
    if (board) {
      return board;
    } else {
      throw new NotAcceptableException({ message: 'Boards are not merged' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/boards/:boardId')
  async getFullBoard(@Request() req, @Param('boardId') boardId: string) {
    let userId = req.user._id;
    let board = await this.BoardService.getBoardFull(boardId, userId);
    if (board) {
      return board;
    } else {
      throw new NotAcceptableException({ message: 'Board is not found' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/boards/:boardId/sections/:sectionId')
  async getFullSection(
    @Request() req,
    @Param('boardId') boardId: string,
    @Param('sectionId') sectionId: string,
  ) {
    let userId = req.user._id;
    let section = await this.BoardService.getSectionFull(
      boardId,
      sectionId,
      userId,
    );
    if (section) {
      return section;
    } else {
      throw new NotAcceptableException({ message: 'section is not found' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Delete('/me/savedPins/:pinId')
  async unsavePinFromBoard(
    @Request() req,
    @Param('pinId') pinId: string,
    @Query('boardId') boardId: string,
    @Query('sectionId') sectionId: string,
  ) {
    let userId = req.user._id;
    let unsavedPin = await this.BoardService.unsavePin(
      pinId,
      boardId,
      sectionId,
      userId,
      false,
    );
    if (unsavedPin) {
      return { success: 'pin is unsaved suucissfully' };
    } else {
      throw new NotAcceptableException({ message: 'pin hasnt been unsaved' });
    }
  }
}
Example #17
Source File: pins.controller.ts    From Phantom with MIT License 4 votes vote down vote up
@UseFilters(HttpExceptionFilter)
@Controller()
export class PinsController {
  constructor(
    private PinsService: PinsService,
    private ImagesService: ImagesService,
    private BoardService: BoardService,
  ) {}

  @UseGuards(AuthGuard('jwt'))
  @Post('/me/pins')
  async createPin(@Request() req, @Body() createPinDto: CreatePinDto) {
    let userId = req.user._id;
    let createdPin = await this.PinsService.createPin(userId, createPinDto);
    if (createdPin) {
      return createdPin;
    } else {
      await this.ImagesService.deleteFile(createPinDto.imageId.toString());
      throw new NotAcceptableException({ message: 'pin is not created' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me/followings/pins')
  async getFollowingPins(@Request() req) {
    let userId = req.user._id;
    let pins = await this.PinsService.getFollowingPins(userId);
    return pins;
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me/pins')
  async getCurrentUserPins(@Request() req) {
    let userId = req.user._id;
    let pins = await this.PinsService.getCurrentUserPins(
      userId,
      true,
      null,
      false,
    );
    if (pins && pins.length != 0) {
      return pins;
    } else {
      throw new NotFoundException({ message: 'no pins' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/user/:userId/pins')
  async getSomeUserPins(@Request() req, @Param('userId') userId: string) {
    let pins = await this.PinsService.getCurrentUserPins(
      userId,
      false,
      null,
      false,
    );
    if (pins && pins.length != 0) {
      return pins;
    } else {
      throw new NotFoundException({ message: 'no pins' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('/me/savedPins/:id')
  async savePin(
    @Request() req,
    @Param('id') pinId: string,
    @Query('boardId') boardId: string,
    @Query('sectionId') sectionId: string,
  ) {
    let userId = req.user._id;
    let savedPin = await this.PinsService.savePin(
      userId,
      pinId,
      boardId,
      sectionId,
    );
    if (savedPin) {
      return { success: true };
    } else {
      throw new NotAcceptableException({ message: 'pin is not saved' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me/savedPins')
  async getCurrentUserSavedPins(@Request() req) {
    let userId = req.user._id;
    let pins = await this.PinsService.getCurrentUserSavedPins(userId);
    if (pins && pins.length != 0) {
      return pins;
    } else {
      throw new NotFoundException({ message: 'no pins' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('/pins/:pinId/comments')
  async createComment(
    @Request() req,
    @Body('commentText') commentText: string,
    @Param('pinId') pinId: string,
  ) {
    let userId = req.user._id;
    let comment = await this.PinsService.createComment(
      pinId,
      commentText,
      userId,
    );
    if (comment) {
      return comment;
    } else {
      throw new NotAcceptableException({ message: 'comment is not created' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('/pins/:pinId/comments/:commentId/replies')
  async createReply(
    @Request() req,
    @Body('replyText') replyText: string,
    @Param('pinId') pinId: string,
    @Param('commentId') commentId: string,
  ) {
    let userId = req.user._id;
    let reply = await this.PinsService.createReply(
      pinId,
      replyText,
      userId,
      commentId,
    );
    if (reply) {
      return reply;
    } else {
      throw new NotAcceptableException({ message: 'reply is not created' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/pins/:pinId/comments')
  async getPinCommentsReplies(@Request() req, @Param('pinId') pinId: string) {
    let userId = req.user._id;
    let comments = await this.PinsService.getPinCommentsReplies(pinId, userId);
    if (comments) {
      return { success: true, comments: comments };
    } else {
      throw new NotFoundException({ message: 'comments not found' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/pins/:pinId')
  async getPinFull(@Request() req, @Param('pinId') pinId: string) {
    let userId = req.user._id;
    let pin = await this.PinsService.getPinFull(pinId, userId);
    if (pin) {
      return pin;
    } else {
      throw new NotFoundException({ message: 'pin not found' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/pins/status/:pinId')
  async getPinStatus(@Request() req, @Param('pinId') pinId: string) {
    let userId = req.user._id;
    let pin = await this.PinsService.checkPinStatus(pinId, userId);
    if (pin) {
      return pin;
    } else {
      throw new NotFoundException({ message: 'pin not found' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Post('/pins/:pinId/reacts')
  async createReact(
    @Request() req,
    @Param('pinId') pinId: string,
    @Query('reactType') reactType: string,
  ) {
    let userId = req.user._id;
    let react = await this.PinsService.createReact(pinId, reactType, userId);
    if (react) {
      return { success: true };
    } else {
      throw new NotAcceptableException({ message: 'react is not created' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('/pins/:pinId/comments/:commentId/likes')
  async likeComment(
    @Request() req,
    @Param('pinId') pinId: string,
    @Param('commentId') commentId: string,
  ) {
    let userId = req.user._id;
    let like = await this.PinsService.likeComment(pinId, commentId, userId);
    if (like) {
      return { success: true };
    } else {
      throw new NotAcceptableException({ message: 'like is not created' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('/pins/:pinId/comments/:commentId/replies/:replyId/likes')
  async likeReply(
    @Request() req,
    @Param('pinId') pinId: string,
    @Param('commentId') commentId: string,
    @Param('replyId') replyId: string,
  ) {
    let userId = req.user._id;
    let like = await this.PinsService.likeReply(
      pinId,
      commentId,
      userId,
      replyId,
    );
    if (like) {
      return { success: true };
    } else {
      throw new NotAcceptableException({ message: 'like is not created' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Delete('/me/pins/:pinId')
  async deletePin(@Request() req, @Param('pinId') pinId: string) {
    let userId = req.user._id;
    let deletedPin = await this.BoardService.deletePin(pinId, userId);
    if (deletedPin) {
      return { success: 'pin is deleted succissfully' };
    } else {
      throw new NotAcceptableException({ message: 'pin is not deleated' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Put('/me/pins/:pinId')
  async editCreatedPin(
    @Request() req,
    @Param('pinId') pinId: string,
    @Body('description') description: string,
    @Body('boardId') boardId: string,
    @Body('sectionId') sectionId: string,
    @Body('title') title: string,
    @Body('destLink') destLink: string,
  ) {
    let userId = req.user._id;
    let editedPin = await this.PinsService.editCreatedPin(
      pinId,
      userId,
      boardId,
      sectionId,
      description,
      title,
      destLink,
    );
    if (editedPin) {
      return editedPin;
    } else {
      throw new NotAcceptableException({ message: 'pin is not edited' });
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Put('/me/savedPins/:pinId')
  async editSavedPin(
    @Request() req,
    @Param('pinId') pinId: string,
    @Body('note') note: string,
    @Body('boardId') boardId: string,
    @Body('sectionId') sectionId: string,
  ) {
    let userId = req.user._id;
    let editedPin = await this.PinsService.editSavedPin(
      pinId,
      userId,
      boardId,
      sectionId,
      note,
    );
    if (editedPin) {
      return { success: 'pin has been edited' };
    } else {
      throw new NotAcceptableException({ message: 'pin is not edited' });
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('/pins/:pinId/report')
  async reportPin(
    @Request() req,
    @Param('pinId') pinId: string,
    @Body('reason') reason: string,
  ) {
    let userId = req.user._id;
    let report = await this.PinsService.reportPin(userId, pinId, reason);
    if (report) {
      return 1;
    } else {
      throw new NotAcceptableException({ message: 'pin is not reported' });
    }
  }
}
Example #18
Source File: recommendation.controller.ts    From Phantom with MIT License 4 votes vote down vote up
@UseFilters(HttpExceptionFilter)
@Controller()
export class RecommendationController {
  constructor(private RecommendationService: RecommendationService) {}
  @UseGuards(AuthGuard('jwt'))
  @Put('/home/me')
  async generateHomeFeed(@Request() req) {
    req.setTimeout(0);
    let userId = req.user._id;
    let home = await this.RecommendationService.homeFeed(userId);
    if (home) {
      return home;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/home')
  async getHomeFeed(
    @Request() req,
    @Query('limit') limit: number,
    @Query('offset') offset: number,
  ) {
    let userId = req.user._id;
    let home = await this.RecommendationService.getHomeFeed(
      userId,
      limit,
      offset,
    );
    if (home) {
      return home;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Put('/more/pins/:pinId')
  async generatePinMore(@Request() req, @Param('pinId') pinId: string) {
    let userId = req.user._id;
    req.setTimeout(0);
    let pins = await this.RecommendationService.pinMoreLike(userId, pinId);
    if (pins) {
      return pins;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/more/pins/:pinId')
  async getPinMore(
    @Request() req,
    @Param('pinId') pinId: string,
    @Query('limit') limit: number,
    @Query('offset') offset: number,
  ) {
    let pins = await this.RecommendationService.getPinMoreLike(
      pinId,
      limit,
      offset,
    );
    if (pins) {
      return pins;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Put('/more/boards/:boardId')
  async generateBoardMoreLike(
    @Request() req,
    @Param('boardId') boardId: string,
  ) {
    let userId = req.user._id;
    req.setTimeout(0);
    let pins = await this.RecommendationService.boardMoreLike(userId, boardId);
    if (pins) {
      return pins;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Put('/more/sections/:boardId/:sectionId')
  async generateSectionMoreLike(
    @Request() req,
    @Param('boardId') boardId: string,
    @Param('sectionId') sectionId: string,
  ) {
    let userId = req.user._id;
    req.setTimeout(0);
    let pins = await this.RecommendationService.sectionMoreLike(
      userId,
      boardId,
      sectionId,
    );
    if (pins) {
      return pins;
    } else {
      throw new NotFoundException();
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/more/boards/:boardId')
  async getBoardMore(
    @Request() req,
    @Param('boardId') boardId: string,
    @Query('limit') limit: number,
    @Query('offset') offset: number,
  ) {
    let pins = await this.RecommendationService.getBoardMoreLike(
      boardId,
      offset,
      limit,
    );
    if (pins) {
      return pins;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/more/sections/:boardId/:sectionId')
  async getSectionMore(
    @Request() req,
    @Param('boardId') boardId: string,
    @Param('sectionId') sectionId: string,
    @Query('limit') limit: number,
    @Query('offset') offset: number,
  ) {
    let pins = await this.RecommendationService.getSectionMoreLike(
      boardId,
      sectionId,
      offset,
      limit,
    );
    if (pins) {
      return pins;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/recommendation/follow')
  async getFollowRecommendation(@Request() req) {
    let userId = req.user._id;
    req.setTimeout(0);
    let follow = await this.RecommendationService.followAllRecommendation(
      userId,
    );
    if (follow) {
      return follow;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/recommendation/topics/:topicName')
  async getTopicRecommendation(
    @Request() req,
    @Param('topicName') topicName: string,
  ) {
    let userId = req.user._id;
    req.setTimeout(0);
    let follow = await this.RecommendationService.topicRecommendation(
      topicName,
      userId,
    );
    if (follow) {
      return follow;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/recommendation/trending')
  async getTrendingRecommendation(@Request() req) {
    let userId = req.user._id;
    req.setTimeout(0);
    let follow = await this.RecommendationService.trendingRecommendation(
      userId,
    );
    if (follow) {
      return follow;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/boardsForYou')
  async getBoardsForYou(@Request() req) {
    let userId = req.user._id;
    req.setTimeout(0);
    let boards = await this.RecommendationService.boardsForYou(userId);
    if (boards) {
      return boards;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/popularPins')
  async getPopularPins(@Request() req) {
    let userId = req.user._id;
    req.setTimeout(0);
    let pins = await this.RecommendationService.popularPins(userId);
    if (pins) {
      return pins;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/pinsForYou')
  async getPinsForYou(@Request() req) {
    let userId = req.user._id;
    req.setTimeout(0);
    let pins = await this.RecommendationService.pinsForYou(userId);
    if (pins) {
      return pins;
    } else {
      throw new NotFoundException();
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/pinsRecentActivity')
  async getPinsRecentActivity(@Request() req) {
    let userId = req.user._id;
    req.setTimeout(0);
    let pins = await this.RecommendationService.pinsInspired(userId);
    if (pins) {
      return pins;
    } else {
      throw new NotFoundException();
    }
  }
}
Example #19
Source File: topic.controller.ts    From Phantom with MIT License 4 votes vote down vote up
@UseFilters(HttpExceptionFilter)
@Controller()
export class TopicController {
  constructor(private TopicService: TopicService) {}
  //get all the topics
  @UseGuards(AuthGuard('jwt'))
  @Get('/topic')
  async getTopics(@Request() req) {
    let userId = req.user._id;
    let topics = await this.TopicService.getTopics(userId);
    if (topics) return topics;
    return new NotFoundException();
  }
  //get a certain topic
  @UseGuards(AuthGuard('jwt'))
  @Get('/topic/:topicId')
  async getTopic(@Request() req, @Param('topicId') topicId: string) {
    let topic = await this.TopicService.getTopicById(topicId);
    if (topic) return topic;
    return new NotFoundException();
  }
  //get all pins of a certain topic
  @UseGuards(AuthGuard('jwt'))
  @Get('/topic/:topicId/pins')
  async getPinsOfAtopic(
    @Request() req,
    @Param('topicId') topicId: string,
    @Query('limit') limit: number,
    @Query('offset') offset: number,
  ) {
    let pins = await this.TopicService.getPinsOfTopic(topicId, limit, offset);
    if (pins && pins.length != 0) return pins;
    return new NotFoundException();
  }
  //add pin to a certain topic
  @UseGuards(AuthGuard('jwt'))
  @Post('/topic/addPin')
  async addPinToAtopic(
    @Body('pinId') pinId: string,
    @Body('topicName') topicName: string,
  ) {
    let topics = await this.TopicService.addPinToTopic(topicName, pinId);
    if (topics) return { message: 'pin has been added successfully!' };
    return new ForbiddenException();
  }
  @UseGuards(AuthGuard('jwt'))
  @Post('/createTopic')
  async createTopic(
    @Body('imageId') imageId: string,
    @Body('imageHeight') imageHeight: number,
    @Body('imageWidth') imageWidth: number,
    @Body('name') name: string,
    @Body('description') description: string,
  ) {
    let topic = await this.TopicService.createTopic(
      imageId,
      description,
      imageWidth,
      imageHeight,
      name,
    );
    if (topic) return topic;
    return new ForbiddenException();
  }

  @Post('/createTopics')
  async createTopics(
    @Body('topics') topics: Array<object>,
    @Body('topics') images: Array<object>,
  ) {
    let topic = await this.TopicService.topicsSeeds(topics);
    if (topic) return topic;
    return new ForbiddenException();
  }
  @Put('/edit')
  async addImageToTopic(@Body('topics') topics: Array<object>) {
    let topic = await this.TopicService.editTopic(topics);
    if (topic) return topic;
    return new ForbiddenException();
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/follow-topic/:topicId')
  async followTopic(@Param() params, @Request() req) {
    if (!(await this.TopicService.followTopic(req.user._id, params.topicId)))
      throw new BadRequestException('can not follow this topic');
  }

  @UseGuards(AuthGuard('jwt'))
  @Delete('/me/follow-topic/:topicId')
  async unfollowTopic(@Param() params, @Request() req) {
    if (!(await this.TopicService.unfollowTopic(req.user._id, params.topicId)))
      throw new BadRequestException('can not unfollow this topic');
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me/follow-topic/:topicId')
  async checkFollowTopic(@Param() params, @Request() req) {
    if (
      !(await this.TopicService.checkFollowTopic(req.user._id, params.topicId))
    )
      return { follow: 'false' };
    return { follow: 'true' };
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me/following-topics')
  async followingTopics(@Request() req) {
    return await this.TopicService.followingTopics(req.user._id);
  }
}
Example #20
Source File: user.controller.ts    From Phantom with MIT License 4 votes vote down vote up
@UseFilters(HttpExceptionFilter)
@Controller()
export class UserController {
  constructor(private userService: UserService, private email: Email) {}

  @UseGuards(AuthGuard('jwt'))
  @Get('users/me')
  async me(@Request() req) {
    const user = await this.userService.getUserMe(req.user._id);

    return user;
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('notifications/me')
  async getNotifications(@Request() req) {
    const user = await this.userService.getUserNotifications(req.user._id);
    return user;
  }
  @Get('/user/:id')
  async getUser(@Param() params) {
    const user = await this.userService.getUserMe(params.id);
    return user;
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/reset-password')
  async resetPassword(
    @Request() req,
    @Body('newPassword') newPassword: string,
    @Body('oldPassword') oldPassword: string,
    @Body('forgetPassword') forgetPassword: Boolean,
  ) {
    if (forgetPassword == true) oldPassword = null;
    else if (!oldPassword)
      throw new HttpException('oldPassword is reqired', HttpStatus.FORBIDDEN);
    const ifRest = await this.userService.resetPassword(
      req.user._id,
      newPassword,
      oldPassword,
    );
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/update')
  async updateUser(@Request() req, @Body() updateData: UpdateDto) {
    await this.userService.checkUpdateData(updateData);
    await this.userService.updateUserInfo(req.user._id, updateData);
    const user = await this.userService.getUserMe(req.user._id);
    user.password = null;
    return user;
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/update-settings')
  async updateUserSettings(
    @Request() req,
    @Body() updateData: UpdateSettingsDto,
  ) {
    if (updateData.notificationCounter)
      return await this.userService.updateDataInUser(req.user._id, {
        notificationCounter: 0,
      });
    await this.userService.updateSettings(req.user._id, updateData);
    if (!updateData.deleteFlag) {
      const user = await this.userService.getUserMe(req.user._id);
      user.password = null;
      return user;
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Put('/me/confirm-update-email')
  async confirmUpdateEmail(@Request() req, @Query('type') type: string) {
    if (!req.user.email || !req.user.newEmail || !req.user._id)
      throw new HttpException('not correct token', HttpStatus.FORBIDDEN);
    if (type === 'changeEmail') {
      const user = await this.userService.checkMAilExistAndFormat(
        req.user.email,
      );
      if (!user)
        throw new HttpException('no user by this email', HttpStatus.FORBIDDEN);
      await this.email.sendEmail(
        req.user.newEmail,
        req.header('Authorization'),
        'set email',
        req.user.firstName,
      );
    } else if (type === 'resetEmail') {
      const user = await this.userService.checkMAilExistAndFormat(
        req.user.newEmail,
      );
      if (user)
        throw new HttpException(
          'this email aleardy exists',
          HttpStatus.FORBIDDEN,
        );
      if (!(await this.userService.setEmail(req.user._id, req.user.newEmail)))
        throw new HttpException(
          'not user or not email',
          HttpStatus.BAD_REQUEST,
        );
    } else if (!type)
      throw new HttpException('type not correct', HttpStatus.FORBIDDEN);
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/boards/view')
  async setViewState(@Request() req, @Query('viewState') viewState: string) {
    const view = await this.userService.setViewState(req.user._id, viewState);
    if (view) {
      return { success: 'view is updated' };
    } else {
      throw new NotAcceptableException('view is not updated');
    }
  }
  @UseGuards(AuthGuard('jwt'))
  @Get('/me/boards/view')
  async getViewState(@Request() req) {
    const view = await this.userService.getViewState(req.user._id);
    if (view) {
      return view;
    } else {
      throw new NotAcceptableException('cant get view state');
    }
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/follow-user/:userId')
  async followUser(@Param() params, @Request() req) {
    if (!(await this.userService.followUser(req.user._id, params.userId)))
      throw new BadRequestException('can not follow this user');
  }

  @UseGuards(AuthGuard('jwt'))
  @Delete('/me/follow-user/:userId')
  async unfollowUser(@Param() params, @Request() req) {
    if (!(await this.userService.unfollowUser(req.user._id, params.userId)))
      throw new BadRequestException('can not follow this user');
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/me/:fcmToken')
  async setFCMToken(@Param() params, @Request() req) {
    const user = await this.userService.updateFCMTocken(
      params.fcmToken,
      req.user._id,
    );
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('/log-out')
  async logOut(@Request() req) {
    const user = await this.userService.updateFCMTocken(' ', req.user._id);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me/follow-user/:userId')
  async checkfollowingUser(@Param() params, @Request() req) {
    const user = await this.userService.getUserById(req.user._id);
    if (!(await this.userService.checkFollowUser(user, params.userId)))
      return { follow: 'false' };
    else return { follow: 'true' };
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me/follower')
  async getFollowers(
    @Request() req,
    @Query('limit') limit: Number,
    @Query('offset') offset: Number,
  ) {
    return await this.userService.userFollowers(req.user._id, limit, offset);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/me/following')
  async getFollowings(
    @Request() req,
    @Query('limit') limit: Number,
    @Query('offset') offset: Number,
  ) {
    return await this.userService.userFollowings(req.user._id, limit, offset);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/:userId/follower')
  async getUserFollowers(
    @Request() req,
    @Param() params,
    @Query('limit') limit: Number,
    @Query('offset') offset: Number,
  ) {
    return await this.userService.userFollowers(params.userId, limit, offset);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('/:userId/following')
  async getUserFollowings(
    @Request() req,
    @Param() params,
    @Query('limit') limit: Number,
    @Query('offset') offset: Number,
  ) {
    return await this.userService.userFollowings(params.userId, limit, offset);
  }

  @Get('/Home/:index')
  async getPublicHome(@Param('index') index: number) {
    let pins = await this.userService.getPublicHome(index);
    return pins;
  }
}