Skip to content

Commit

Permalink
Adiciona API gRPC de atualização parcial por parâmetros
Browse files Browse the repository at this point in the history
  • Loading branch information
IgorCastilhos committed Feb 15, 2024
1 parent 41e20fa commit 4271e06
Show file tree
Hide file tree
Showing 12 changed files with 651 additions and 93 deletions.
1 change: 1 addition & 0 deletions db/query/user.sql
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ LIMIT 1;
UPDATE users
SET
hashed_password = coalesce(sqlc.narg(hashed_password), hashed_password),
password_changed_at = coalesce(sqlc.narg(password_changed_at), password_changed_at),
full_name = coalesce(sqlc.narg(full_name), full_name),
email = coalesce(sqlc.narg(email), email)
WHERE
Expand Down
17 changes: 10 additions & 7 deletions db/sqlc/user.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion doc/statik/statik.go

Large diffs are not rendered by default.

65 changes: 62 additions & 3 deletions doc/swagger/bank_application.swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"swagger": "2.0",
"info": {
"title": "Bank Application API",
"version": "1.1",
"version": "1.2",
"contact": {
"name": "Igor Castilhos",
"url": "https://github.com/IgorCastilhos",
Expand All @@ -23,8 +23,8 @@
"paths": {
"/v1/create_user": {
"post": {
"summary": "Cria um novo usuário",
"description": "Use essa API para criar um novo usuário",
"summary": "Criar usuário",
"description": "Use essa API para criar um usuário",
"operationId": "Bank_CreateUser",
"responses": {
"200": {
Expand Down Expand Up @@ -88,6 +88,40 @@
"Bank"
]
}
},
"/v1/update_user": {
"patch": {
"summary": "Atualizar usuário",
"description": "Use essa API para atualizar um usuário",
"operationId": "Bank_UpdateUser",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/pbUpdateUserResponse"
}
},
"default": {
"description": "An unexpected error response.",
"schema": {
"$ref": "#/definitions/rpcStatus"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/pbUpdateUserRequest"
}
}
],
"tags": [
"Bank"
]
}
}
},
"definitions": {
Expand Down Expand Up @@ -152,6 +186,31 @@
}
}
},
"pbUpdateUserRequest": {
"type": "object",
"properties": {
"username": {
"type": "string"
},
"fullName": {
"type": "string"
},
"email": {
"type": "string"
},
"password": {
"type": "string"
}
}
},
"pbUpdateUserResponse": {
"type": "object",
"properties": {
"user": {
"$ref": "#/definitions/pbUser"
}
}
},
"pbUser": {
"type": "object",
"properties": {
Expand Down
92 changes: 92 additions & 0 deletions grpcApi/rpc_update_user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package grpcApi

import (
"context"
"errors"
db "github.com/IgorCastilhos/BankApplication/db/sqlc"
"github.com/IgorCastilhos/BankApplication/pb"
"github.com/IgorCastilhos/BankApplication/utils"
"github.com/IgorCastilhos/BankApplication/validation"
"github.com/jackc/pgx/v5/pgtype"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"time"
)

func (server *Server) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserResponse, error) {
// Todo: adicionar autorização
violations := validateUpdateUserRequest(req)
if violations != nil {
return nil, invalidArgumentError(violations)
}

// Se for válido...
arg := db.UpdateUserParams{
Username: req.GetUsername(),
FullName: pgtype.Text{
String: req.GetFullName(),
Valid: req.FullName != nil,
},
Email: pgtype.Text{
String: req.GetEmail(),
Valid: req.Email != nil,
},
}

if req.Password != nil {
hashedPassword, err := utils.HashPassword(req.GetPassword())
if err != nil {
return nil, status.Errorf(codes.Internal, "falhou ao fazer o hash da senha: %s", err)
}

arg.HashedPassword = pgtype.Text{
String: hashedPassword,
Valid: true,
}

arg.PasswordChangedAt = pgtype.Timestamptz{
Time: time.Now(),
Valid: true,
}
}

user, err := server.store.UpdateUser(ctx, arg)
if err != nil {
if errors.Is(err, db.ErrRecordNotFound) {
return nil, status.Errorf(codes.NotFound, "usuário não encontrado")
}
return nil, status.Errorf(codes.Internal, "falhou ao criar um usuário: %s", err)
}

response := &pb.UpdateUserResponse{
User: convertUser(user),
}
return response, nil
}

func validateUpdateUserRequest(request *pb.UpdateUserRequest) (violations []*errdetails.BadRequest_FieldViolation) {
if err := validation.ValidateUsername(request.GetUsername()); err != nil {
violations = append(violations, fieldViolation("username", err))
}

if request.Password != nil {
if err := validation.ValidatePassword(request.GetPassword()); err != nil {
violations = append(violations, fieldViolation("password", err))
}
}

if request.FullName != nil {
if err := validation.ValidateFullName(request.GetFullName()); err != nil {
violations = append(violations, fieldViolation("full_name", err))
}
}

if request.Email != nil {
if err := validation.ValidateEmail(request.GetEmail()); err != nil {
violations = append(violations, fieldViolation("email", err))
}
}

return violations
}
Loading

0 comments on commit 4271e06

Please sign in to comment.