Main.scala 2.1 KB
Newer Older
D
Dejan Mijić 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright 2021 John A. De Goes and the ZIO contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17 18
package example

P
Paul Daniels 已提交
19
import com.typesafe.config.ConfigFactory
20
import example.api.Api
D
Dejan Mijić 已提交
21
import example.config.{AppConfig, ServerConfig}
P
Paul Daniels 已提交
22 23
import sttp.client3.asynchttpclient.zio.AsyncHttpClientZioBackend
import zhttp.service.server.ServerChannelFactory
D
Dejan Mijić 已提交
24
import zhttp.service.{EventLoopGroup, Server}
25 26

import zio._
P
Paul Daniels 已提交
27
import zio.config.getConfig
28 29 30 31
import zio.config.syntax._
import zio.config.typesafe.TypesafeConfig
import zio.console._
import zio.logging.Logging
P
Paul Daniels 已提交
32
import zio.magic._
33
import zio.redis.RedisExecutor
A
Anatoly Sergeev 已提交
34 35
import zio.redis.codec.StringUtf8Codec
import zio.schema.codec.Codec
36 37 38

object Main extends App {

P
Paul Daniels 已提交
39 40 41 42
  private val config = TypesafeConfig.fromTypesafeConfigM[Any, Throwable, AppConfig](
    ZIO.effect(ConfigFactory.load().getConfig("example")),
    AppConfig.descriptor
  )
43

P
Paul Daniels 已提交
44 45
  private val serverConfig = config.narrow(_.server)
  private val redisConfig  = config.narrow(_.redis)
46

P
Paul Daniels 已提交
47 48 49 50
  private val codec = ZLayer.succeed[Codec](StringUtf8Codec)
  private val redis = Logging.ignore ++ redisConfig ++ codec >>> RedisExecutor.live
  private val sttp  = AsyncHttpClientZioBackend.layer()
  private val cache = redis ++ sttp >>> ContributorsCache.live
51

P
Paul Daniels 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65
  def run(args: List[String]): URIO[ZEnv, ExitCode] =
    getConfig[ServerConfig]
      .flatMap(conf =>
        (Server.port(conf.port) ++ Api.routes).make
          .use_(putStrLn("Server online.") *> ZIO.never)
      )
      .injectCustom(
        serverConfig,
        cache,
        ServerChannelFactory.auto,
        EventLoopGroup.auto(0)
      )
      .tapError(e => putStrLn(e.getMessage))
      .exitCode
66
}