@nestjs/common#Patch TypeScript Examples
The following examples show how to use
@nestjs/common#Patch.
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: transaction.controller.ts From bank-server with MIT License | 6 votes |
@Patch('confirm')
@HttpCode(HttpStatus.NO_CONTENT)
@Roles(RoleType.USER, RoleType.ADMIN, RoleType.ROOT)
@ApiNoContentResponse({
description: 'confirm transfer',
})
async confirmTransaction(
@AuthUser() user: UserEntity,
@Body() confirmTransactionDto: ConfirmTransactionDto,
): Promise<void> {
await this._transactionService.confirmTransaction(
user,
confirmTransactionDto,
);
}
Example #2
Source File: profile.controller.ts From office-hours with GNU General Public License v3.0 | 6 votes |
@Patch()
async patch(
@Body() userPatch: UpdateProfileParams,
@User(['courses', 'courses.course', 'phoneNotif', 'desktopNotifs'])
user: UserModel,
): Promise<GetProfileResponse> {
user = Object.assign(user, userPatch);
// check that the user is trying to update the phone notifs
if (userPatch.phoneNotifsEnabled && userPatch.phoneNumber) {
// only register new phone if the notifs are enables and the phone number is new
if (
user.phoneNotifsEnabled &&
userPatch.phoneNumber !== user.phoneNotif?.phoneNumber
) {
await this.notifService.registerPhone(userPatch.phoneNumber, user);
}
}
await user.save();
return this.get(user);
}
Example #3
Source File: insights.controller.ts From office-hours with GNU General Public License v3.0 | 6 votes |
@Patch('')
@Roles(Role.PROFESSOR)
async toggleInsightOn(
@Body() body: { insightName: string },
@User() user: UserModel,
): Promise<void> {
await this.insightsService.toggleInsightOn(user, body.insightName);
return;
}
Example #4
Source File: course.controller.ts From office-hours with GNU General Public License v3.0 | 6 votes |
@Patch(':id/edit_course')
@UseGuards(JwtAuthGuard, CourseRolesGuard)
@Roles(Role.PROFESSOR)
async editCourseInfo(
@Param('id') courseId: number,
@Body() coursePatch: EditCourseInfoParams,
): Promise<void> {
await this.courseService.editCourse(courseId, coursePatch);
}
Example #5
Source File: alerts.controller.ts From office-hours with GNU General Public License v3.0 | 6 votes |
@Patch(':alertId')
@Roles(Role.STUDENT, Role.TA, Role.PROFESSOR)
async closeAlert(@Param('alertId') alertId: number): Promise<void> {
const alert = await AlertModel.findOne({
where: {
id: alertId,
},
});
if (!alert) {
throw new BadRequestException(
ERROR_MESSAGES.alertController.notActiveAlert,
);
}
alert.resolved = new Date();
await alert.save();
}
Example #6
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Enable one user
* @param ids User ID integer
* @example DELETE /users/1/enable
*/
@ApiTags('Users single operation')
@ApiOperation({
summary: 'Enable user - Batch',
description: 'Enable user. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiParam({ name: 'id', required: true, type: 'number', example: '1' })
@Patch(':id/enable')
async enable(@Param('id') id: number) {
return await this.service.enable(id);
}
Example #7
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Disable user
* @param ids User ID integer
* @example DELETE /users/1/disable
*/
@ApiTags('Users single operation')
@ApiOperation({
summary: 'Disable user - single',
description: 'Disable user. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiParam({ name: 'id', required: true, type: 'number', example: '1' })
@Patch(':id/disable')
async disable(@Param('id') id: number) {
return await this.service.disable(id);
}
Example #8
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Restore softdeleted user
* @param ids User ID integer
* @example DELETE /users/1/restore
*/
@ApiTags('Users single operation')
@ApiOperation({
summary: 'Restore user - Batch',
description: 'Restore user. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiParam({ name: 'id', required: true, type: 'number', example: '1' })
@Patch(':id/restore')
async restore(@Param('id') id: number) {
return await this.service.restore(id);
}
Example #9
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Enable users
* @param ids User ID integers ?ids=1,2,3
* @example DELETE /users/bulk/enable?ids=1,2,3
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Enable users - Batch',
description: 'Enable users. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
@Patch('bulk/enable')
async enableMany(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
return await this.service.enableMany(ids);
}
Example #10
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Disable users
* @param ids User ID integers ?ids=1,2,3
* @example DELETE /users/bulk/disable?ids=1,2,3
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Disable users - Batch',
description: 'Disable users. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
@Patch('bulk/disable')
async disableMany(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
return await this.service.disableMany(ids);
}
Example #11
Source File: users.controller.ts From nestjs-starter with MIT License | 6 votes |
/**
* Restore softdeleted users
* @param ids User ID integers ?ids=1,2,3
* @example DELETE /users/bulk/restore?ids=1,2,3
*/
@ApiTags('Users batch operations')
@ApiOperation({
summary: 'Restore users - Batch',
description: 'Restore users. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
})
@ApiOkResponse({ status: 200, description: 'Success response' })
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
@ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
@ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
@Patch('bulk/restore')
async restoreMany(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
return await this.service.restoreMany(ids);
}
Example #12
Source File: tenant.controller.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Patch('/:tenantUuid')
@Permissions('settings/update')
@AuditLog('settings/update')
@ApiOkResponse({ type: Tenant })
public async patch(@Body() updatedTenant: any): Promise<Tenant> {
const existingTenant = await this.tenantService.findOne();
return this.tenantService.update(existingTenant.uuid, omit(['users', 'features'])({
...existingTenant,
...updatedTenant,
settings: {
...existingTenant.settings,
...reject(equals('hidden'))({
...updatedTenant.settings,
something: "hidden"
})
},
updatedAt: new Date(),
}) as any);
}
Example #13
Source File: user.controller.ts From bank-server with MIT License | 6 votes |
@Patch('/')
@UseGuards(AuthGuard, RolesGuard)
@UseInterceptors(AuthUserInterceptor)
@ApiBearerAuth()
@Roles(RoleType.USER, RoleType.ADMIN, RoleType.ROOT)
@HttpCode(HttpStatus.OK)
@ApiResponse({
status: HttpStatus.OK,
description: 'Update user',
type: UserDto,
})
async setUserData(
@AuthUser() user: UserEntity,
@Body() userUpdateDto: UserUpdateDto,
): Promise<UserDto> {
const userWithNewData = await this._userService.updateUserData(
user,
userUpdateDto,
);
return userWithNewData.toDto();
}
Example #14
Source File: message.controller.ts From bank-server with MIT License | 6 votes |
@Patch('/')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiResponse({
status: HttpStatus.NO_CONTENT,
description: 'Readed message',
type: MessageDto,
})
@Roles(RoleType.USER, RoleType.ADMIN, RoleType.ROOT)
async readMessage(
@AuthUser() user: UserEntity,
@Body() readMessageDto: ReadMessageDto,
): Promise<MessageDto | any> {
return this._messageService.readMessages(user, readMessageDto);
}
Example #15
Source File: auth.controller.ts From bank-server with MIT License | 6 votes |
@Patch('password/reset')
@ApiBearerAuth()
@UseGuards(JwtResetPasswordGuard)
@HttpCode(HttpStatus.NO_CONTENT)
@ApiNoContentResponse({
status: HttpStatus.NO_CONTENT,
description: 'Successfully reseted password',
})
@Transactional()
async resetPassword(
@Body() { password }: UserResetPasswordDto,
@Req() { user },
) {
return this._authService.handleResetPassword(password, user);
}
Example #16
Source File: auth.controller.ts From bank-server with MIT License | 6 votes |
@Patch('logout')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiNoContentResponse({
description: 'Successfully Logout',
})
@UseGuards(AuthGuard, RolesGuard)
@UseInterceptors(AuthUserInterceptor)
@ApiBearerAuth()
@Roles(RoleType.USER, RoleType.ADMIN, RoleType.ROOT)
async userLogout(@AuthUser() user: UserEntity): Promise<void> {
await this._userAuthService.updateLastLogoutDate(user.userAuth);
}
Example #17
Source File: todo.controller.ts From postgres-nest-react-typescript-boilerplate with GNU General Public License v3.0 | 6 votes |
@Patch('/update')
updateTodo(
@Query('id') id: string,
@Req() req,
@Body() data: Partial<TodoDTO>,
) {
const userId = req.user.id;
return this.todoService.updateTodo(userId, id, data);
}
Example #18
Source File: user.controller.ts From nestjs-starter-rest-api with MIT License | 6 votes |
// TODO: ADD RoleGuard
// NOTE : This can be made a admin only endpoint. For normal users they can use PATCH /me
@Patch(':id')
@ApiOperation({
summary: 'Update user API',
})
@ApiResponse({
status: HttpStatus.OK,
type: SwaggerBaseApiResponse(UserOutput),
})
@ApiResponse({
status: HttpStatus.NOT_FOUND,
type: BaseApiErrorResponse,
})
@UseInterceptors(ClassSerializerInterceptor)
async updateUser(
@ReqContext() ctx: RequestContext,
@Param('id') userId: number,
@Body() input: UpdateUserInput,
): Promise<BaseApiResponse<UserOutput>> {
this.logger.log(ctx, `${this.updateUser.name} was called`);
const user = await this.userService.updateUser(ctx, userId, input);
return { data: user, meta: {} };
}
Example #19
Source File: article.controller.ts From nestjs-starter-rest-api with MIT License | 6 votes |
@Patch(':id')
@ApiOperation({
summary: 'Update article API',
})
@ApiResponse({
status: HttpStatus.OK,
type: SwaggerBaseApiResponse(ArticleOutput),
})
@UseInterceptors(ClassSerializerInterceptor)
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
async updateArticle(
@ReqContext() ctx: RequestContext,
@Param('id') articleId: number,
@Body() input: UpdateArticleInput,
): Promise<BaseApiResponse<ArticleOutput>> {
const article = await this.articleService.updateArticle(
ctx,
articleId,
input,
);
return { data: article, meta: {} };
}
Example #20
Source File: users.controller.ts From mamori-i-japan-api with BSD 2-Clause "Simplified" License | 6 votes |
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
@ApiOperation({ summary: 'Update user profile' })
@ApiOkResponse({ type: NoResponseBody })
@Patch('/me/profile')
async patchMeProfile(
@Request() req,
@Body() updateUserProfileDto: UpdateUserProfileDto
): Promise<void> {
updateUserProfileDto.userId = req.user.uid
return this.usersService.updateUserProfile(updateUserProfileDto)
}
Example #21
Source File: prefectures.controller.ts From mamori-i-japan-api with BSD 2-Clause "Simplified" License | 6 votes |
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
@ApiOperation({ summary: 'Update prefecture' })
@ApiOkResponse({ type: NoResponseBody })
@ApiNotFoundResponse()
@Patch('/prefectures/:prefectureId')
async patchMeProfile(
@Request() req,
@Param('prefectureId') prefectureId: number,
@Body() updatePrefectureRequest: UpdatePrefectureRequestDto
): Promise<NoResponseBody> {
const requestAdminUser: RequestAdminUser = req.user
updatePrefectureRequest.prefectureId = prefectureId
await this.prefecturesService.updateOnePrefecture(requestAdminUser, updatePrefectureRequest)
return {}
}
Example #22
Source File: question.controller.ts From office-hours with GNU General Public License v3.0 | 6 votes |
@Patch('resolveGroup/:group_id')
@Roles(Role.TA, Role.PROFESSOR)
async resolveGroup(
@Param('group_id') groupId: number,
@UserId() instructorId: number,
): Promise<void> {
const group = await QuestionGroupModel.findOne({
where: {
id: groupId,
},
relations: ['questions', 'questions.taHelped', 'questions.creator'],
});
for (const question of group.questions) {
// only resolve q's that weren't requeued/can't find
if (question.status === OpenQuestionStatus.Helping) {
await this.questionService.changeStatus(
QuestionStatusKeys.Resolved,
question,
instructorId,
);
}
}
return;
}
Example #23
Source File: queue.controller.ts From office-hours with GNU General Public License v3.0 | 6 votes |
@Patch(':queueId')
@Roles(Role.TA, Role.PROFESSOR)
async updateQueue(
@Param('queueId') queueId: number,
@Body() body: UpdateQueueParams,
): Promise<QueueModel> {
const queue = await this.queueService.getQueue(queueId);
if (queue === undefined) {
throw new NotFoundException();
}
queue.notes = body.notes;
queue.allowQuestions = body.allowQuestions;
try {
await queue.save();
} catch (err) {
console.error(err);
throw new HttpException(
ERROR_MESSAGES.queueController.saveQueue,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
return queue;
}
Example #24
Source File: broadcast.controller.ts From twilio-voice-notification-app with Apache License 2.0 | 6 votes |
/**
* PATCH /broadcasts/:cancel
* Cancels the broadcast
* Any call with status In-progress, Ringing, Initiated and Queued is changed
* to Canceled so that it never happens.
* @param id The id of the broadcast
*/
@UseGuards(AuthGuard)
@Patch(':id/cancel')
async cancelBroadcast(@Param('id') id: string): Promise<Broadcast> {
return this.broadcastService.cancelBroadcast(id);
}
Example #25
Source File: tagGroup.controller.ts From whispr with MIT License | 5 votes |
@Patch(':id')
@HttpCode(204)
@UsePipes(new ValidationPipe({ whitelist: true }))
async updateTagGroup(@Param('id') id: string, @Body() tagGroup: TagGroupInputType): Promise<ITagGroup> {
return this.tagGroupService.update(id, tagGroup);
}
Example #26
Source File: question.controller.ts From office-hours with GNU General Public License v3.0 | 5 votes |
@Patch(':questionId')
@Roles(Role.STUDENT, Role.TA, Role.PROFESSOR)
// TODO: Use queueRole decorator, but we need to fix its performance first
async updateQuestion(
@Param('questionId') questionId: number,
@Body() body: UpdateQuestionParams,
@UserId() userId: number,
): Promise<UpdateQuestionResponse> {
let question = await QuestionModel.findOne({
where: { id: questionId },
relations: ['creator', 'queue', 'taHelped'],
});
if (question === undefined) {
throw new NotFoundException();
}
const isCreator = userId === question.creatorId;
if (isCreator) {
// Fail if student tries an invalid status change
if (body.status && !question.changeStatus(body.status, Role.STUDENT)) {
throw new UnauthorizedException(
ERROR_MESSAGES.questionController.updateQuestion.fsmViolation(
'Student',
question.status,
body.status,
),
);
}
question = Object.assign(question, body);
try {
await question.save();
} catch (err) {
console.error(err);
throw new HttpException(
ERROR_MESSAGES.questionController.saveQError,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
return question;
}
// If not creator, check if user is TA/PROF of course of question
const isTaOrProf =
(await UserCourseModel.count({
where: {
userId,
courseId: question.queue.courseId,
role: In([Role.TA, Role.PROFESSOR]),
},
})) > 0;
if (isTaOrProf) {
if (Object.keys(body).length !== 1 || Object.keys(body)[0] !== 'status') {
throw new UnauthorizedException(
ERROR_MESSAGES.questionController.updateQuestion.taOnlyEditQuestionStatus,
);
}
await this.questionService.validateNotHelpingOther(body.status, userId);
return await this.questionService.changeStatus(
body.status,
question,
userId,
);
} else {
throw new UnauthorizedException(
ERROR_MESSAGES.questionController.updateQuestion.loginUserCantEdit,
);
}
}
Example #27
Source File: notification.controller.ts From aws-nestjs-starter with The Unlicense | 5 votes |
@Patch(':id')
update(@Param('id') id: string, @Body() body: UpdateNotificationInput) {
return this.notificationService.update({ id }, body);
}
Example #28
Source File: whisp.controller.ts From whispr with MIT License | 5 votes |
@Patch(':id')
@HttpCode(204)
@UsePipes(new ValidationPipe({ whitelist: true }))
async update(@Param('id') id: string, @Body() whisp: WhispInputType): Promise<IWhisp> {
return this.whispService.update(id, whisp);
}
Example #29
Source File: tag.controller.ts From whispr with MIT License | 5 votes |
@Patch(':id')
@HttpCode(204)
@UsePipes(new ValidationPipe({ whitelist: true }))
async updateTag(@Param('id') id: string, @Body() tag: TagInputType): Promise<ITag> {
return this.tagService.update(id, tag);
}