@nestjs/common#HttpStatus TypeScript Examples

The following examples show how to use @nestjs/common#HttpStatus. 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: user.controller.ts    From nestjs-api-example with MIT License 8 votes vote down vote up
@Get(':id')
  @ApiOperation({ summary: '유저 정보 조회 API' })
  @ApiOkResponse({
    description: 'Id가 일치하는 유저 정보를 조회한다.',
    type: UserResponseDto,
  })
  async findOne(
    @Param('id', new ParseIntPipe()) id: number,
    @Res() res: Response,
  ) {
    const responseDto = await this.userService.findById(id);

    return res.status(HttpStatus.OK).json(instanceToPlain(responseDto));
  }
Example #2
Source File: plugin-newsletter.controller.ts    From Cromwell with MIT License 7 votes vote down vote up
@Post('subscribe')
    /** Use ThrottlerGuard to limit number of requests from one IP address. Allow max 4 requests in 20 seconds: */
    @UseGuards(ThrottlerGuard)
    @Throttle(4, 20)
    @ApiOperation({ description: 'Post email to subscribe for newsletters' })
    @ApiResponse({
        status: 200,
        type: Boolean,
    })
    @ApiBody({ type: PluginNewsletterSubscription })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async placeSubscription(@Body() input: PluginNewsletterSubscription): Promise<boolean | undefined> {
        const email = input?.email;
        if (!email || !/\S+@\S+\.\S+/.test(email)) {
            throw new HttpException(`Invalid email`, HttpStatus.BAD_REQUEST);
        }

        const hasSubscribed = await getManager().findOne(PluginNewsletter, {
            where: {
                email
            }
        });
        if (hasSubscribed) return true;

        const newsletter = new PluginNewsletter();
        newsletter.email = email;
        await getManager().save(newsletter);
        return true;
    }
Example #3
Source File: whisp.service.ts    From whispr with MIT License 7 votes vote down vote up
private static fillTTL(whisp: WhispInputType, updated: Date): { timeToLiveSec: number; expirationDate: Date } {
    const expDate = new Date(updated);
    if (whisp.expirationDate) {
      return { timeToLiveSec: null, expirationDate: whisp.expirationDate };
    }

    if (whisp.timeToLive) {
      let ttl = Number(whisp.timeToLive);

      if (Number.isNaN(ttl)) {
        ttl = parse(whisp.timeToLive, 's');
      }

      if (!ttl || ttl < 1) {
        throw new HttpException(
          'time to live must be positive number of seconds or a parsable time string like 2min,1hour',
          HttpStatus.BAD_REQUEST,
        );
      } else {
        expDate.setSeconds(expDate.getSeconds() + ttl);
        return { timeToLiveSec: ttl, expirationDate: expDate };
      }
    } else {
      return { timeToLiveSec: null, expirationDate: null };
    }
  }
Example #4
Source File: auth.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('reset-password')
  @HttpCode(HttpStatus.OK)
  async resetPassword(@Body() input: ResetPassInput): Promise<void> {
    const { email, token, newPassword } = input;
    const exist = await this.usersService.findOneAsync({ email });
    if (!exist) throw new UnauthorizedException('Password reset failed');
    await this.authService.validatePasswordToken({
      userId: exist.id,
      plainToken: token,
      newPassword
    });
  }
Example #5
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiNoContentResponse({
    description: 'no content',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiInternalServerErrorResponse({ description: '500. InternalServerError' })
  @ApiBearerAuth()
  @Delete('logout-all')
  @UseGuards(RolesGuard)
  @Roles(RolesEnum.admin)
  @HttpCode(HttpStatus.NO_CONTENT)
  async logoutAll(): Promise<{}> {
    return this.authService.deleteAllTokens();
  }
Example #6
Source File: user.controller.ts    From nestjs-api-example with MIT License 6 votes vote down vote up
@Delete(':id')
  @ApiOperation({ summary: '유저 삭제 API' })
  @ApiNoContentResponse({ description: 'Id가 일치하는 유저 정보를 삭제한다.' })
  async delete(
    @Param('id', new ParseIntPipe()) id: number,
    @Res() res: Response,
  ) {
    await this.userService.deleteUser(id);

    return res.status(HttpStatus.NO_CONTENT).send();
  }
Example #7
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiNoContentResponse({
    description: 'no content',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiBearerAuth()
  @Delete('logout-all')
  @UseGuards(RolesGuard)
  @Roles(RolesEnum.admin)
  @HttpCode(HttpStatus.NO_CONTENT)
  async logoutAll(): Promise<{}> {
    return this.authService.deleteAllTokens();
  }
Example #8
Source File: theme.service.ts    From Cromwell with MIT License 6 votes vote down vote up
private async deleteTheme(themeName: string): Promise<boolean> {
        const pckgOld = await getModulePackage(themeName);
        const oldVersion = pckgOld?.version;
        if (!themeName || !oldVersion) throw new HttpException('Plugin package not found', HttpStatus.INTERNAL_SERVER_ERROR);

        await runShellCommand(`yarn remove ${themeName} --non-interactive`);
        await sleep(1);

        const pckgNew = await getModulePackage(themeName);
        if (pckgNew) throw new HttpException(`Failed to remove theme's package`, HttpStatus.INTERNAL_SERVER_ERROR);

        const themeRepo = getCustomRepository(GenericTheme.repository);
        const entity = await this.findOne(themeName);
        if (entity?.id) await themeRepo.deleteEntity(entity.id);

        await serverFireAction('uninstall_theme', { themeName });
        return true;
    }
Example #9
Source File: test-auth-utils.ts    From barista with Apache License 2.0 6 votes vote down vote up
export async function getAccessToken(app: INestApplication) {
  const authInfo = {username: 'anyusername', password: 'anypass'};
  const response = await request(app.getHttpServer())
    .post('/user/login')
    .send(authInfo);
  expect(response.status).toBe(HttpStatus.CREATED);
  return response.body.accessToken;
}
Example #10
Source File: theme.service.ts    From Cromwell with MIT License 6 votes vote down vote up
async handleThemeUpdate(themeName: string): Promise<boolean> {
        if (await this.cmsService.getIsRunningNpm()) {
            throw new HttpException('Only one install/update available at the time', HttpStatus.METHOD_NOT_ALLOWED);
        }
        await this.cmsService.setIsRunningNpm(true);
        await this.cmsService.checkYarn();

        const transactionId = getRandStr(8);
        startTransaction(transactionId);

        let success = false;
        let error: any;
        try {
            success = await this.updateTheme(themeName)
        } catch (e) {
            error = e;
            success = false;
        }

        if (success) await this.cmsService.installModuleDependencies(themeName);

        endTransaction(transactionId);
        await this.cmsService.setIsRunningNpm(false);

        if (!success) {
            throw new HttpException(error?.message, error?.status);
        }
        return true;
    }
Example #11
Source File: create-user.http.controller.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
@Post(routesV1.user.root)
  @ApiOperation({ summary: 'Create a user' })
  @ApiResponse({
    status: HttpStatus.OK,
    type: IdResponse,
  })
  @ApiResponse({
    status: HttpStatus.CONFLICT,
    description: UserAlreadyExistsError.message,
  })
  @ApiResponse({
    status: HttpStatus.BAD_REQUEST,
  })
  async create(@Body() body: CreateUserRequest): Promise<IdResponse> {
    const command = new CreateUserCommand(body);

    const result: Result<
      ID,
      UserAlreadyExistsError
    > = await this.commandBus.execute(command);

    // Deciding what to do with a Result (similar to Rust matching)
    // if Ok we return a response with an id
    // if Error decide what to do with it depending on its type
    return match(result, {
      Ok: id => new IdResponse(id.value),
      Err: error => {
        if (error instanceof UserAlreadyExistsError)
          throw new ConflictException(error.message);
        throw error;
      },
    });
  }
Example #12
Source File: store.service.ts    From Cromwell with MIT License 6 votes vote down vote up
async createPaymentSession(input: CreateOrderDto): Promise<OrderTotalDto> {
        const total = await this.calcOrderTotal(input);
        total.cart = total.cart?.filter(item => item?.product);

        if (!total.cart?.length) throw new HttpException('Cart is invalid or empty', HttpStatus.BAD_REQUEST);
        const settings = await getCmsSettings();

        const payments = await serverFireAction('create_payment', total);
        total.paymentOptions = [...Object.values(payments ?? {}),
        ...(!settings?.disablePayLater ? [
            payLaterOption,
        ] : []),];

        return total;
    }
Example #13
Source File: find-users.http.controller.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
@Get(routesV1.user.root)
  @ApiOperation({ summary: 'Find users' })
  @ApiResponse({
    status: HttpStatus.OK,
    type: UserResponse,
  })
  async findUsers(@Body() request: FindUsersRequest): Promise<UserResponse[]> {
    const query = new FindUsersQuery(request);
    const result: Result<UserEntity[], Error> = await this.queryBys.execute(
      query,
    );

    /* Returning Response classes which are responsible
       for whitelisting data that is sent to the user */
    return result.unwrap().map(user => new UserResponse(user));
  }
Example #14
Source File: plugin.service.ts    From Cromwell with MIT License 6 votes vote down vote up
async installPlugin(pluginName: string): Promise<boolean> {
        const info = await this.getPluginLatest(pluginName);
        if (!pluginName || !info || !info.packageVersion || !info.version) throw new HttpException('Plugin was not found', HttpStatus.METHOD_NOT_ALLOWED);

        const settings = await getCmsSettings();
        const isBeta = !!settings?.beta;
        const version = isBeta ? (info.betaVersion ?? info.version) : info.version;

        await runShellCommand(`yarn add ${pluginName}@${version} --exact --non-interactive`);
        await sleep(1);

        const pluginPckgNew = await getModulePackage(pluginName);
        if (!pluginPckgNew?.version) throw new HttpException('Plugin package was not found', HttpStatus.INTERNAL_SERVER_ERROR);

        const pluginExports = (await readPluginsExports()).find(p => p.pluginName === pluginName);
        if (!pluginExports) throw new HttpException('Plugin in not a CMS module', HttpStatus.INTERNAL_SERVER_ERROR);

        if (pluginExports.backendPath && await fs.pathExists(pluginExports.backendPath)) {
            // If plugin has backend, we need to apply it by restarting API server
            // Using "Safe reload" will switch to a new server only if it successfully started:
            const resp1 = await childSendMessage('make-new');
            if (resp1.message !== 'success') {
                // Rollback
                await runShellCommand(`yarn remove ${pluginName} --non-interactive`);
                await sleep(1);

                throw new HttpException('Could not start server with the new plugin', HttpStatus.INTERNAL_SERVER_ERROR);
            } else {
                const resp2 = await childSendMessage('apply-new', resp1.payload);

                if (resp2.message !== 'success') throw new HttpException('Could not start server with the new plugin', HttpStatus.INTERNAL_SERVER_ERROR);

                setPendingKill(2000);
            }
        }

        await this.activatePlugin(pluginName);
        return true;
    }
Example #15
Source File: app.utils.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
VALIDATION_PIPE = new ValidationPipe({
  errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
})
Example #16
Source File: cms.service.ts    From Cromwell with MIT License 6 votes vote down vote up
public async getAdminConfig() {
        const config = await getCmsSettings();
        const info = await getCmsInfo();
        if (!config) {
            throw new HttpException('CmsController::getPrivateConfig Failed to read CMS Config', HttpStatus.INTERNAL_SERVER_ERROR);
        }
        const dto = new AdminCmsConfigDto().parseConfig(config);
        dto.cmsInfo = info;
        try {
            const robotsPath = resolve(getPublicDir(), 'robots.txt');
            if (await fs.pathExists(robotsPath))
                dto.robotsContent = (await fs.readFile(robotsPath)).toString();
        } catch (error) {
            logger.error(error);
        }
        return dto;
    }
Example #17
Source File: system.controller.spec.ts    From amplication with Apache License 2.0 6 votes vote down vote up
describe('SystemController', () => {
  let app: INestApplication;

  beforeEach(async () => {
    jest.clearAllMocks();
    const moduleRef = await Test.createTestingModule({
      imports: [MorganModule.forRoot()],
      providers: [
        {
          provide: BuildService,
          useClass: jest.fn(() => ({
            updateRunningBuildsStatus: mockUpdateRunningBuildsStatus
          }))
        },
        {
          provide: DeploymentService,
          useClass: jest.fn(() => ({
            updateRunningDeploymentsStatus: mockUpdateRunningDeploymentsStatus,
            destroyStaledDeployments: mockDestroyStaledDeployments
          }))
        }
      ],
      controllers: [SystemController]
    }).compile();

    app = moduleRef.createNestApplication();
    await app.init();
  });

  it('should update statuses', async () => {
    await request(app.getHttpServer())
      .post('/system/update-statuses')
      .expect(HttpStatus.CREATED);
    expect(mockUpdateRunningBuildsStatus).toBeCalledTimes(1);
    expect(mockUpdateRunningBuildsStatus).toBeCalledWith();
    expect(mockUpdateRunningDeploymentsStatus).toBeCalledTimes(1);
    expect(mockUpdateRunningDeploymentsStatus).toBeCalledWith();
  });
});
Example #18
Source File: order.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
@Authorized<TAuthRole>("all")
    @Query(() => Order)
    async [getOneByIdPath](
        @Ctx() ctx: TGraphQLContext,
        @Arg("id", () => Int) id: number
    ): Promise<Order | undefined> {
        if (!ctx?.user?.role) throw new HttpException('Access denied.', HttpStatus.UNAUTHORIZED);

        const order = await this.repository.getOrderById(id);
        if (ctx.user.role === 'guest' || ctx.user.role === 'administrator' ||
            (order?.userId && ctx.user.id + '' === order.userId + ''))
            return order;
    }
Example #19
Source File: auth.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('send-password-reset-token')
  @HttpCode(HttpStatus.OK)
  async sendForgotPwToken(@Body() input: AcctVerifyDto): Promise<void> {
    const { clientBaseUrl, tokenParamName, emailParamName, email } = input;

    const user = await this.usersService.findOneAsync({ email });
    if (!user) return;
    const token = await this.authService.generateTempToken({
      user,
      type: TokenType.PASSWORD,
      expiresInMins: 10
    });
    if (!token) return;
    const url = new URL(clientBaseUrl);
    url.searchParams.set(tokenParamName, token);
    url.searchParams.set(emailParamName, email);
    const html = `<p>Hello ${user.fullName}, please reset your password <a href=${url.href}>here</a></p>`;
    this.mailService.sendMailAsync({
      from: configuration().appEmail,
      to: user.email,
      html,
      date: new Date(Date.now())
    });
  }
Example #20
Source File: google-recaptcha-network-exception.spec.ts    From google-recaptcha with MIT License 6 votes vote down vote up
describe('Google recaptcha network exception', () => {
    test('Test without error code', () => {
        const exception = new GoogleRecaptchaNetworkException();
        expect(exception.getStatus()).toBe(HttpStatus.INTERNAL_SERVER_ERROR);
        expect(exception.message).toBe('Unknown network error.');
    });

    test('Test with error code', () => {
        const errCode = 'ECONNRESET';
        const exception = new GoogleRecaptchaNetworkException(errCode);
        expect(exception.getStatus()).toBe(HttpStatus.INTERNAL_SERVER_ERROR);
        expect(exception.message.toString().includes(errCode)).toBeTruthy();
    });
});
Example #21
Source File: auth-guards.ts    From Cromwell with MIT License 6 votes vote down vote up
graphQlAuthChecker = (
    options?: {
        root?: any;
        args?: Record<string, any>;
        context?: TGraphQLContext;
        info?: any;
    } | null,
    roles?: TAuthRole[] | null,
) => {
    const { root, args, context, info } = options ?? {};
    if (!roles || roles.length === 0) return true;
    if (getStoreItem('cmsSettings')?.installed === false) return true;

    const userInfo: TAuthUserInfo | undefined = (context as TGraphQLContext)?.user;

    if (!userInfo?.id || !userInfo?.role)
        throw new HttpException('Access denied', HttpStatus.UNAUTHORIZED);

    if (!matchRoles(userInfo, roles, args?.id)) throw new HttpException('Access denied', HttpStatus.FORBIDDEN);

    return true;
}
Example #22
Source File: error.dto.ts    From aqualink-app with MIT License 6 votes vote down vote up
errorTemplates: Record<number, ErrorResponse> = {
  [HttpStatus.BAD_REQUEST]: {
    statusCode: HttpStatus.BAD_REQUEST,
    message: 'Validation failed',
    error: 'Bad Request',
  },
  [HttpStatus.UNAUTHORIZED]: {
    statusCode: HttpStatus.UNAUTHORIZED,
    message: 'Not authorized',
    error: 'Unauthorized',
  },
  [HttpStatus.NOT_FOUND]: {
    statusCode: HttpStatus.NOT_FOUND,
    message: 'Resource not found',
    error: 'Not Found',
  },
}
Example #23
Source File: attribute.repository.ts    From Cromwell with MIT License 6 votes vote down vote up
async updateAttribute(id: number, updateAttribute: TAttributeInput): Promise<Attribute> {
        logger.log('AttributeRepository::updateAttribute; id: ' + id);

        const attribute = await this.getById(id, ['values']);
        if (!attribute) throw new HttpException(`Attribute ${id} not found!`, HttpStatus.NOT_FOUND);

        await this.handleAttributeInput(attribute, updateAttribute, 'update');
        await this.save(attribute);
        return attribute;
    }