leobenkel / laeta   0.1.0

MIT License Website GitHub

Agnostic service registry with fully typed retrieval

Scala versions: 2.13

License: MIT Gitter release-badge maven-central-badge CI-CD BCH compliance Coverage Status Mutation testing badge

Laeta

Small library to handle registery of services.

Handle collection of Services of arbitrary type and retrieve them fully typed.

Laeta (wikipedia)

Table of Contents

Created by gh-md-toc

How to use?

Add to build.sbt

First include the library in your project:

libraryDependencies += "com.leobenkel" %% "laeta" % "[VERSION]"

With version being: maven-central-badge

Setup

Live example: Scastie-0P5GodpCSSmL5Pd8igL0tA or take a look at the test example

You need two pieces for the compiler to start guiding you:

A service:

import com.leobenkel.laeta.Service

case class MyService(override val input: INPUT) extends Service[INPUT, MyService] {
 ???
}

And a factory:

import com.leobenkel.laeta.ServiceFactory

case class MyFactory(override val getInput: Int) extends ServiceFactory[INPUT, MyService] {
    lazy override protected val getObject: ServiceConstructor[INPUT, MyService] = MyConstructor
    lazy override protected val getType:   ServiceType[MyService] = MyGeyKey
}

This will force you to create:

A constructor:

object MyConstructor extends ServiceConstructor[INPUT, MyService]

Your MyConstructor should probably have the same name as case class MyService so you don't have to implement the apply method.

and a Type:

case object MyGeyKey extends ServiceType[MyService] {}

To use

And to use is very simple, you first register all the factories:

val registryBuilder: RegistryFactories = RegistryFactories()
    .register(MyFactory(input))

and then you seal the registry:

val registryReady: ServiceCollection = registryBuilder.create

you can now access any service, anywhere, typed !

val myService = registryReady.getService(MyGeyKey)

Notes

It is possible to merge the ServiceConstructor[INPUT, MyService] and the ServiceType[MyService] for shorter code.

This mean you can replace all the places where we used MyGeyKey by MyConstructor.

Example on Scastie-716dNpMORwuJqO9RWED93A.