Created
May 9, 2018 11:21
-
-
Save deepankar14693/9fdae28e99755412dbbb3f781332bbe5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import akka.actor.ActorSystem | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.model._ | |
import akka.http.scaladsl.server.Directives._ | |
import akka.stream.ActorMaterializer | |
import scala.concurrent.ExecutionContextExecutor | |
//the usual config code required for an Akka Http server, mixing in our JsonHelper trait too | |
object Routes extends App with JsonHelper { | |
implicit val system: ActorSystem = ActorSystem("my-system") | |
implicit val materializer: ActorMaterializer = ActorMaterializer() | |
// needed for the future flatMap/onComplete in the end | |
implicit val executionContext: ExecutionContextExecutor = system.dispatcher | |
val studentsClass = new Students | |
val route = | |
pathPrefix("demo") { | |
get { | |
path("fetchAllStudents") { | |
complete { | |
val addedStudents = studentsClass.fetchStudents | |
val jsonResponse = write(addedStudents) | |
/* json for list of Students | |
[{"rollNum":1,"name":"Ayush"},{"rollNum":2,"name":"deepankar"}] | |
*/ | |
HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, jsonResponse)) | |
} | |
} | |
} ~ | |
post { | |
path("addStudent") { | |
entity(as[String]) { studentJson => { | |
complete { | |
val studentRecord = parse(studentJson).extract[studentsClass.Student] | |
/* | |
Student(3,randhir) | |
*/ | |
val updatedList = studentsClass.addStudent(studentRecord) | |
val jsonResponse = write(updatedList) | |
HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, jsonResponse)) | |
} | |
} | |
} | |
} | |
} ~ | |
put { | |
//for updating student name student roll number has to be same as entered previously | |
path("updateStudent") { | |
entity(as[String]) { studentJson => { | |
complete { | |
val studentRecord = parse(studentJson).extract[studentsClass.Student] | |
val updatedList = studentsClass.updateStudent(studentRecord) | |
val jsonResponse = write(updatedList) | |
HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, jsonResponse)) | |
} | |
} | |
} | |
} | |
} ~ | |
delete { | |
path("deleteStudent" / IntNumber) { rollNum => | |
complete { | |
val deleteRecord = studentsClass.deleteStudent(rollNum) | |
val jsonResponse = write(deleteRecord) | |
HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, jsonResponse)) | |
} | |
} | |
} | |
} | |
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) | |
println(s"Server online at http://localhost:8080") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment