ps0604
ps0604

Reputation: 1081

Dynamic path routing in Play for Scala

I have 300 entries defined in routes file, like so:

GET /url001 MyClass.myMethod

This works with URLs such as http://localhost:9000/url001

Now, I need to define two environments for these 300 links, for production and testing. The links would be like:

http://localhost:9000/prod/url001

for production (see prod in the path)

and

http://localhost:9000/test/url001

for testing (see test in the path).

I want to have a single set of links in routes, how can this be achieved in Play? I know that I can define a variable in the path, such as path/:var, but what I need is to set a relative URL.

Note: Some users may be using prod while others may be using test simultaneously

Upvotes: 3

Views: 1065

Answers (2)

Ion Cojocaru
Ion Cojocaru

Reputation: 2583

Instead of having as set of repeated routes which would introduce a lot of copy/paste code, maybe it's better to have a role based logic. Assuming that there is some kind of session management/user identification mechanism set in place, then the test users can have test credentials, that when logged in will have a role/session attribute to indicate the test only capabilities. Ideally you would have different dedicated instances, since it already looks like they are used for different things.

Upvotes: 1

Andriy Kuba
Andriy Kuba

Reputation: 8263

You can use the SIRD (String Interpolating Routing DSL): https://www.playframework.com/documentation/2.6.x/ScalaSirdRouter#Binding-sird-Router

You will need to describe that 30 entries in the scala source, then do the two records in routes and bind them to your scala custom router.

The custom router will looks like:

package my.app

import javax.inject.Inject

import play.api.mvc._
import play.api.routing.Router.Routes
import play.api.routing.SimpleRouter
import play.api.routing.sird._

class MainRouter @Inject()(controller: ApiController)
  extends SimpleRouter
{
  override def routes: Routes = {
    case GET(p"/url001") => MyClass.myMethod001
    case GET(p"/url002") => MyClass.myMethod002
  }
}

The conf/routes will look like:

/prod                        my.app.MainRouter
/test                        my.app.MainRouter

Still, you need somehow to understand what is what inside the app, I do not know what is your idea - session (cookies) or tokens or...

Because the test environment will not be used to actually test the system. It's for a business intelligence application where the user will test the queries they build before migrating them to production. From the system perspective, both prod and test are production. From the user perspective, prod and test are different environments

In this case, I will advise you to create two different installments.

Upvotes: 2

Related Questions