Friday, February 9, 2018

Minimal Scala Play

If you just need Scala Play for some quick testing/demo of Scala code, even the Scala Play Starter Example is too heavy. It has a lot of example code that is not needed and too much security for something to be run and accessed only locally.

Here is how to trim down the Scala Play Starter Example. First is the conf/application.conf file. All that is needed for the whole file is:

play.filters {
  hosts { allowed = ["."] }
  headers { contentSecurityPolicy = "default-src * 'unsafe-inline'" }
}

The hosts.allowed allows connections from external sources, and headers.contentSecurityPolicy allows things like remotely hosted Javascript (e.g. http://code.jquery.com/jquery-3.3.1.min.js) and Javascript inline directly in HTML elements (i.e. disable CSP and go back to 2016).

Then the conf/routes file:

GET     /                controllers.HomeController.index
GET     /mywebservice    controllers.MyWebServiceController.get(inputdata)

Specifically, you can delete the /count and /message routes, and then add whatever routes you need for web services (like /mywebservice above).

In the app directory:

rm -rf filters
rm -rf services
rm Module.scala
rm controllers/AyncController.scala
rm controllers/CountController.scala
rm views/main.scala.html
rm views/welcome.scala.html

And then in views/index.scala.html you can just delete all the code therein and write your own regular HTML and not bother with the Twirl template language if you don't need it.

Finally, you'll need to create controllers/MyWebServiceController.scala. You can use HomeController.scala as a template and add in import play.api.libs.json._ to gain access to the Play JSON APIs for parsing and generating JSON.

controllers/MyWebServiceController.scala

package controllers

import javax.inject._
import play.api.libs.json._
import play.api.mvc._

@Singleton
class MyWebServiceController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def get(inputdata:String) = Action {
    val a = Json.parse(inputdata)
    val r = // do stuff with a
    Ok(Json.toJson(r))
  }
}

No comments: