Skip to content

Commit

Permalink
ChangesSharedController
Browse files Browse the repository at this point in the history
  • Loading branch information
QuesitoCode committed Oct 11, 2023
1 parent eca7f39 commit 56f0caa
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 68 deletions.
Binary file not shown.
Binary file not shown.
Binary file not shown.
68 changes: 23 additions & 45 deletions src/main/scala/example/controllers/SharedController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
package controllers

import scalikejdbc._
import models.{SharedModel}
import models.SharedModel

import io.circe._
import io.circe.generic.auto._
Expand All @@ -15,63 +15,41 @@ import scala.concurrent.duration._
class SharedController {
implicit val session: DBSession = AutoSession

def guardarCompartido(
archivos: List[( Int, Int, Int)]
): Future[List[Either[String, SharedModel]]] = {
Future.sequence {
archivos.map { case (usuario_id, archivo_id) =>
Future {
try {
val result =
sql"INSERT INTO compartidos (usuario_id, archivo_id) VALUES ($usuario_id, $archivo_id)"
.update()
def guardarCompartido(usuario_id: Int, archivo_id: Int): Future[Either[String, SharedModel]] = {

if (result > 0) {
// Recupera el ID generado por la base de datos
val generatedId: Long = sql"SELECT LAST_INSERT_ID()".map(rs => rs.long(1)).single().getOrElse(0L)
Future {
try {
val result =
sql"INSERT INTO compartidos (usuario_id, archivo_id) VALUES ($usuario_id, $archivo_id)"
.update()

// Crea una instancia de DirectoryModel con el ID real
val comparitdo = SharedModelModel(generatedId.toInt, usuario_id, archivo_id)
Right(comparitdo)
} else {
Left("No se pudo agregar el compartido")
}
} catch {
case e: Exception =>
println(s"Error interno del servidor: ${e.getMessage}")
Left("Error interno del servidor")
}
if (result > 0) {
// Recupera el ID generado por la base de datos
val generatedId: Long = sql"SELECT LAST_INSERT_ID()".map(rs => rs.long(1)).single().getOrElse(0L)

// Crea una instancia de DirectoryModel con el ID real
val comparitdo = SharedModel(generatedId.toInt, usuario_id, archivo_id)
Right(comparitdo)
} else {
Left("No se pudo agregar el compartido")
}
} catch {
case e: Exception =>
println(s"Error interno del servidor: ${e.getMessage}")
Left("Error interno del servidor")
}
}
}

}

def eliminarCompartido(id: Int): Future[Either[String, SharedModel]] = {
def eliminarCompartido(id: Int): Future[Either[String, String]] = {
Future {
try {
// Realizar la actualización para cambiar el campo "habilitado" a false
val resultado = sql"DELETE from compartido WHERE id = $id".update()

if (resultado > 0) {

val resultadoFuture: Future[Either[String, FileModel]] = obtenerCompartidosPorUsuario(id)

val resultado: Either[String, FileModel] = Await.result(resultadoFuture, 5.seconds)

resultado match {
case Right(fileModel) =>
// Aquí puedes trabajar con el resultado Right (éxito)
// Por ejemplo, imprimir el archivo
println(s"Archivo encontrado: $fileModel")
Right(fileModel)
case Left(errorMessage) =>
// Aquí puedes manejar el caso Left (error)
// Por ejemplo, imprimir el mensaje de error
println(s"Error: $errorMessage")
Left(errorMessage)
}

Right("Se eliminó el archivo correctamente")

} else {
// La actualización no afectó ninguna fila, devolver un mensaje de error
Expand Down
11 changes: 7 additions & 4 deletions src/main/scala/example/main.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.typesafe.config.ConfigFactory
import scalikejdbc.ConnectionPool
import controllers.{UserController, FileController, DirectoryController}
import routes.{UserRoute, FileRoute, DirectoryRoute}
import models.{UserModel, FileModel, DirectoryModel}
import controllers.{UserController, FileController, DirectoryController, SharedController}
import routes.{UserRoute, FileRoute, DirectoryRoute, SharedRoute}
import models.{UserModel, FileModel, DirectoryModel, SharedModel}
import example.DatabaseConfig

object Main extends App {
Expand All @@ -29,7 +29,10 @@ object Main extends App {
val directoryController = new DirectoryController
val directoryRoute = new DirectoryRoute(directoryController)

val routes: Route = userRoute.route ~ fileRoute.route ~ directoryRoute.route
val sharedController = new SharedController
val sharedRoute = new SharedRoute(sharedController)

val routes: Route = userRoute.route ~ fileRoute.route ~ directoryRoute.route ~ sharedRoute.route

val bindingFuture = Http().bindAndHandle(routes, "0.0.0.0", 80)
println(s"Server online at http://207.248.81.126:80/")
Expand Down
10 changes: 6 additions & 4 deletions src/main/scala/example/models/SharedAllModel.scala
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package models

case class SharedModel(

id: Int,
usuario_id_id: Int,
usuario_id: Int,
archivo_id: Int
)


)
case class SharedCreateModel(
usuario_id: Int,
archivo_id: Int
)
24 changes: 9 additions & 15 deletions src/main/scala/example/routes/SharedRoute.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class SharedRoute(SharedController: SharedController) {
path(IntNumber) { id =>
val result: Future[Either[String, sharedModel]] = SharedController.buscarUsuario(id)
onSuccess(result) {
case Right(shared) => complete(shared)
case Right(shared) => complete(shared)
case Left(errorMessage) => complete(HttpResponse(StatusCodes.NotFound, entity = errorMessage))
}
}
Expand All @@ -26,32 +26,26 @@ class SharedRoute(SharedController: SharedController) {
post {
entity(as[sharedCreateModel]) { shared =>
val result: Future[Either[String, sharedModel]] =
SharedController.guardarCompartido(shared.usuario_id, archivo_id)
SharedController.guardarCompartido(shared.usuario_id, shared.archivo_id)
onSuccess(result) {
case Right(newshared) => complete(StatusCodes.Created, newshared)
case Right(newshared) => complete(StatusCodes.Created, newshared)
case Left(errorMessage) => complete(HttpResponse(StatusCodes.InternalServerError, entity = errorMessage))
}
}
}
} ~
path("delete") {
put {
entity(as[List[Int]]) { ids =>
val result: Future[List[Either[String, sharedModel]]] = SharedController.eliminarCompartido(ids)
onSuccess(result) { resultList =>
val errors = resultList.collect { case Left(errorMessage) => errorMessage }
if (errors.isEmpty) {
val shareds = resultList.collect { case Right(shared) => shared }
complete(StatusCodes.OK, shareds)
} else {
complete(HttpResponse(StatusCodes.InternalServerError, entity = errors.mkString(", ")))

}
entity(as[sharedCreateModel]) { id =>
val result: Future[Either[String, sharedModel]] = SharedController.eliminarCompartido(id)
onSuccess(result) {
case Right(newshared) => complete(StatusCodes.Created, newshared)
case Left(errorMessage) => complete(HttpResponse(StatusCodes.InternalServerError, entity = errorMessage))
}
}
}

}

}
}

0 comments on commit 56f0caa

Please sign in to comment.