• Stars
    star
    14
  • Rank 1,391,726 (Top 29 %)
  • Language
    Scala
  • Created over 7 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A common interface for different Id types

idid

idid is a common interface for different Id types. It allows you to define distinct types for each of your Id types, even though they might have the same backing type (Int, Long, UUID, etc).

Reasoning

Imagine you have a project with several entities, and they, in some cases, share the same base type of Id. For instance, if you have a Customer entity and Product, both them might have Ids, and they might be an Int, Long, or perhaps an UUID. For example, they might look like this:

case class Customer(id: Int, /*...*/)

case class Product(id: Int, /*...*/)

And perhaps, at some point, you might have a method that receives multiple Ids. Take for example:

def isProductInBasket(customerId: Int, productId: Int) = ???

And that's when things start to get confusing. Simply swapping your parameters might cause a lot of undesired headaches and debugging sessions. And that's when you start to wonder, "isn't Scala a typed language? How can I make it differently"? Wouldn't you like to have different types for different Ids, even though their backing type is the same, and therefore allow the compiler to figure out that something is wrong in your code?

There are many ways to do that, but we were looking for a way that would be generic enough that you could have a base type and easily parse different Id types. Consider, for instance, you are using Play, and you have REST endpoints for the different entities, each having a specific Id type on the path. You don't want to write a binder for each of them, but instead it would be much nicer to have a common one that can parse them all. The same applies for writing those Ids to the database with, let's say, Slick and custom type mappers.

Example

The example above could be written as the following:

import com.unstablebuild.idid._

case class CustomerId(underlying: Int) extends TypedId[Int]
implicit val customerIdFactory = Id.factory[CustomerId]

case class ProductId(underlying: Int) extends TypedId[Int]
implicit val customerIdFactory = Id.factory[ProductId]

case class Customer(id: CustomerId, /*...*/)
case class Product(id: ProductId, /*...*/)

def isProductInBasket(customerId: CustomerId, productId: ProductId) = ???

So far, that doesn't look like much. The magic, though, starts when using the Id object directly.

// Create an Id
val customerId = Id.create[CustomerId](123)

// Create random Ids
val customerId = Id.random[CustomerId]

// Parse from a String
val customerId = Id.parse[CustomerId]("123")

// Create from a default value (empty), i.e. 0
val customerId = Id.empty[CustomerId]

// Get its value
val underlyingId = Id.value(customerId)

This way, when you need to create something like a Play binder, you could declare it this way:

def idBinder[T <: Id : IdFactory] = new PathBindable[T] { /*...*/ }

It's import to point out that you can still use your Id class normally. We also advice to put your Id types and their factories on a Package Object, so they can be accessed more easily.

Auto Generated Factories

Instead of declaring a companion variable for each of your Id classes, one can instead use the implicit factory generator provided by com.unstablebuild.idid.factory.AutoIdFactory or the com.unstablebuild.idid.auto package. For instance:

object MyIds extends AutoIdFactory {
  case class MyId(underlying: Int) extends TypedId[Int]
}

import MyIds._
val id = Id.random[MyId]

or

case class MyId(underlying: Int) extends TypedId[Int]
  
import com.unstablebuild.idid.auto._
val id = Id.random[MyId]

Sources

Default values for the underlying Id types, how to parse them, or how random values are generated, are specific by instances of IdSource. A source is select through an implicit binding. Default sources are defined for the following types:

  • UUID
  • Int
  • Long
  • BigInt
  • String

If you require a type that is not available, all you have to do is declare your own implicit source. To give an example, the source for an Int looks like the following

implicit val intSource: IdSource[Int] = new IdSource[Int] {
  override def random: Int = Random.nextInt()
  override def parse(str: String): Int = str.toInt
  override def empty: Int = 0
}

Integrating

Comparator

implicit def idOrdering[T <: Id](implicit ordering: Ordering[T#UID]): Comparator[T] =
    Ordering.by[T, T#UID](_.underlying)

Play Path Binding

implicit def idBinder[T <: Id : IdFactory] = new PathBindable[T] {

  override def bind(key: String, value: String): Either[String, T] =

    Try(Id.parse[T](value)).toOption.toRight(s"Could not convert $value into ID")

  override def unbind(key: String, id: T): String =
    id.toString

}

Play Json Format

implicit def idFormat[T <: Id](implicit factory: IdFactory[T], format: Format[T#UID]): Format[T] = new Format[T] {
  override def writes(id: T): JsValue = format.writes(id.underlying)
  override def reads(json: JsValue): JsResult[T] = json.validate[T#UID].map(Id.create[T])
}

Slick Mapper

The following will create a mapper from any defined type who also has also has a valid BaseColumnType in Slick:

implicit def uuidMapper[T <: Id : IdFactory : ClassTag](implicit baseColumnType: BaseColumnType[T#UID]) =
    MappedColumnType.base[T, T#UID](_.underlying, Id.create[T])

Install

To use it with SBT, add the following to your build.sbt file:

resolvers += Resolver.sonatypeRepo("public")

libraryDependencies += "com.unstablebuild" %% "idid" % "0.2.0"

Contributors

Special thanks to Christian Wilhelm for the ideas behind this project.

Release

./sbt +test +macros/test
./sbt +publishSigned +macros/publishSigned
./sbt sonatypeReleaseAll

More Repositories

1

coapex

CoAP protocol in Elixir
Elixir
12
star
2

autobreaker

Automatically wrap Scala classes that return Futures with a Circuit Breaker
Scala
9
star
3

settler

boilerplate-free typed settings generation in Scala
Scala
6
star
4

SuperMarket

Agile Brazil 2011 presentation content
Java
5
star
5

akka-cluster-examples

A few examples using akka-cluster
Scala
4
star
6

draw-diagram

Generate Syntax Diagrams from simplified BNF rules
JavaScript
4
star
7

Mendeley-Importer-for-Safari

A simple button to let you import references and documents to you Mendeley Library with a single click.
JavaScript
4
star
8

s3mp

Simple Serial Slave-Master Protocol (S3MP)
4
star
9

reindxr

automatically (re)index files inside a folder using Apache Lucene
Scala
3
star
10

ircbot

simple bot that connects to a IRC room and save the transcripts to a txt file
Scala
3
star
11

ditado

Distributed Issue Tracker
Ruby
3
star
12

nginx-route-testing

Test routes declared on your nginx configuration
Python
3
star
13

filesyncher

Scala
2
star
14

scala-groovy_presentation

JavaScript
2
star
15

TicTacToe

game
Java
2
star
16

scala-jsonr

A very simple library to create JSON strings in Scala
Scala
2
star
17

query-parser

parse advanced search queries using antlr4
JavaScript
2
star
18

golang-sks

Simple Key Store
Go
2
star
19

jcmph

Small experiment to crete a Java/Scala API to CMPH (C Minimal Perfect Hashing) Library.
C
2
star
20

code-an

Git/Jira code analyser
Scala
2
star
21

ScalaMines

The Mines game made in Scala
Scala
2
star
22

distributedHappyNumberFinder

Scala
1
star
23

dotfiles-control

Shell
1
star
24

irclog-dist

crazy, but works: it packs irclog, reindxr and ircbot all together
Shell
1
star
25

mapmytweets

Show in a map the tweets of a given account.
Ruby
1
star
26

scala-freenode-search

search the freenode scala channel history
Scala
1
star
27

code-an-gui

JavaScript
1
star
28

elixir-mines

minesweeper in elixir
Elixir
1
star
29

latest-build

JavaScript
1
star
30

pot

Page Object Tester
Ruby
1
star
31

dotfiles

Shell
1
star
32

ReflectionSpike

small experiences with java reflection
Java
1
star
33

theses-search

theses-search
JavaScript
1
star
34

irclog

play application to display content indexed by reindxr
Scala
1
star
35

moca

a distributed crawler capable of rendering pages with javascript
Scala
1
star
36

client-ui

experiments with angularjs, grunt, bower, etc and how can they be applied on our project
JavaScript
1
star
37

view-logs

a silly webserver to return log files in crystal
Crystal
1
star
38

brew-cask-explorer

explore the homepage of packages in homebrew-cask
JavaScript
1
star
39

grooveshark-lyrics-safari

safari plugin for http://nettofarah.github.com/grooveshark-lyrics/
JavaScript
1
star
40

scala-function-pipeline

A parallel pipeline of Scala functions
Scala
1
star
41

capitalism_with_zmq

ZMQ examples
Ruby
1
star
42

dotvim

.vim files
Vim Script
1
star
43

ScalatraInGAE

base project to run scalatra in Google App Engine [need to modify appengine-web.xml]
1
star
44

grooveshark-lyrics

spike to get the lyrics for the current song on grooveshark
JavaScript
1
star
45

rust-bananapi-dht11

A DHT11 driver using Rust for Banana Pi
Rust
1
star
46

textmate_theme

My TextMate theme
1
star
47

1st_Scala

experiences with Scala, ScalaTest and ScalaIDE
Scala
1
star
48

analytics-with-spark

Exercises for the book "Advanced Analytics with Spark"
Shell
1
star
49

mifare-card-reader

Access control using a gumstix board and a Mifare card reader. The access log is accessible through a web interface
C
1
star
50

torri.co

personal website
JavaScript
1
star
51

WebScalaMines

The ScalaMines, but now at your browser
JavaScript
1
star