Coder Social home page Coder Social logo

finagle / finch Goto Github PK

View Code? Open in Web Editor NEW
1.6K 60.0 221.0 8.89 MB

Scala combinator library for building Finagle HTTP services

Home Page: https://finagle.github.io/finch

License: Apache License 2.0

Scala 99.44% Shell 0.56%
finch finagle scala http json circe web rest

finch's People

Contributors

akozhemiakin avatar arron-green avatar benfradet avatar benjumanji avatar benwhitehead avatar bskern avatar chbrown avatar crispywalrus avatar derrickburns avatar diebauer avatar ilya-murzinov avatar jenshaase avatar jorokr21 avatar magicknot avatar mimilei avatar n4to4 avatar nicmart avatar omerzach avatar prayagupa avatar rpless avatar scala-steward avatar sergeykolbasov avatar tarossi avatar tomjadams avatar tpetillot avatar travisbrown avatar travisbrown-stripe avatar vkostyukov avatar wennergr avatar yanana avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

finch's Issues

Lightweight in-memory caching API

Probably based on standard CHM.

It may looks like a finagled filter that a) checks the local cache and then b) performs request handling:

object User extends Endpoint {
  def route {
    case Method.GET -> Root / "users" => RetrieveFromCache("all-users") andThen GetAllUsers
  }
}

Replace Facets with Filters or Services

It's better to keep the number of builing blocks as small as possible. It looks like we realy don't need a special Facet entity - we can use either pure Filter-s of pure Service-s for this.

The goal is to keep the API unchanged.

New method names

Endpoint {
  def serveAt(port)(fn): Server
  def exposeWith(fn): Service[HttpRequest, HttpResponse]
}
implicit def prepareEndpoint(respond: Endpoint[HttpRequest, JsonResponse]): Endpoint[HttpRequest, HttpResponse] = {
    respond afteThat TurnJsonIntoHttp
 }

Http.serve(":8081", endpoint.toService)

What is Finch 0.0.1?

Finch 0.0.1

  • is just a single scala file pacakge.scala (I have to put everything insinde a single file)
  • supports HtttService and type-parametrized HttpServiceOf[A]
  • has a Resource that exposes a route and might be composed with either orElse or andThen
  • has a Facet that converts service's responses
  • facets are composable with afterThat method
  • supports JsonArray and JsonObject
  • provides two facets: TrunJsonToHttp and WrapJsonWithMetaAsTag
  • has a RestApi runnable-class with exposeAt(port) method

This should take 100-200 SLOC.

Composable ValidationRule's

for {
 e <- RequiredParam("email")
 p <- RequiredParam("password")
 _ <- "password" shouldNot "be empty" when { p.nonEmpty }
 _ <- "password" should "be longer then 10 symbols" when { p.length > 10 }
} yield (e, p)

New composable entity that changes req type

It might be called a Sink.

trait Sink[-ReqIn, +ReqOut] {
  def afterThat(next: Sink[]): Sink
  def afterThat(service: Service): Service
  def afterThat(resource: RestResource): RestResourse
}

The usage looks as follows:

val b = a afterThat service

ParamFetcher as Reader Monad

Something like this:

val credentials: ParamFetcher[(String, String)] = for {
  name <- Fetch("name", "*".r)
  password <- Fetch("password", "*".r)
} yield (name, password)

val f: Future[(String, String)] = credentials(request) handle {
  case e: ParamFetchError => 
   // e.wrongParams: Map[String, String]
   // Map("name" -> "No param.", "password" -> "Does not match.") 
  ("1", "2") // default values
}

Abstracting over JSON libraries

scala.util.parsing.json is deprecated in 2.11, and there are lots of better JSON ASTs and serializers around these days. Would you be interested in a pull request that makes the JSON library pluggable?

Add ParamValidator

val credentials = for {
  n <- RequiredParam("name")
  p <- RequiredParam("pass")
} yield (n, p)

val validator = for {
  n <- Validator(...) // name validator
  p <- Validator(...) // password validator
} yield (n, p)

for {
  (name, pass) <- credentials(req)
  _ <- validator(name, pass)
}

New Json API

JsonPath("a.b.c.d" -> 10) = 
  JsonObject(
    "a" -> JsonObject(
      "b" -> JsonObject(
        "c" -> JsonOnject(
           "d" -> 10
 ))))

Support loopback requests

Finch should be able to resolve loopback request w/o a network stack. This might be implemented as a function in RestApi class that delivers the requests to a backend service directly:

object Api extends RestApi {
  def port = 8080
  def resource = A orElse B orElse C
  Await.ready(this) 
}

Json Facet with Formatter

The default TurnJsonIntoHttp should use a default formatter. However, users should be able to pass their own formatters into a facet. The API shoudn't change.

Think about how users will define their own requests

Sometimes it make sense to use a Scala type-checker in order to write a type-safe filters within a custom request-type. The most popular example - having an AuthorizedHttpRequest instead of HttpRequest. Users should be able to do that with Finch.

Add empty request readers

def a: RequestReader[Option[Unit]] = NoParams
def b: FutureRequestReader[Unit]  = NoRequiredParams
def c: FutureRequestReader[Option[Unit]] = NoOptionalParams

Refactor Implicit Classes

There should a way to hide all the implicit classes from users. The comminon sense: they shouldn't be listed in IDE autocoplition on io.finch. expression but still should alter the requered values with new methods. I'm not shure whether this possible or not.

Add LICENSE

I would use the same LICENSE as Finagle essentially, Apache Public License 2.0 :)

Can we use Reader Monad for Json transformations?

It looks crazy. I need a json-reader-monad to fight this:

val feedbacksWithAttachments = feedbacks flatMap { seq =>
      Future.collect(seq.map { o =>
        val id = o.get[Int]("id")
        o.flatMapTagInFuture[JSONObject]("feedback") { f =>
          f.flatMapTagInFuture[JSONArray]("attachments") { _ =>
            for {
              query <- client.prepare("select a.id, a.sent, a.path, a.description from attachments a join " +
                                      "feedback_attachments fa on a.id=fa.fid_attachment join feedbacks f on " +
                                      "f.id=fa.fid_feedback where f.id=$1 limit $2")
              rep <- query.select(id, Config[Int]("api.innerArraySizeLimit")) { row =>
                JsonObject(
                  "id" -> row.get[Int]("id"),
                  "uri" -> row.get[String]("path"),
                  "sent" -> Gmt(row.get[Timestamp]("sent")),
                  "description" -> row.get[String]("description")
                )
              }
            } yield JsonArray(rep)
          }
        }
      })
    }

JsonObject.group

I should thing about implementing this code as JsonObject function:

val rep: Seq[JSONObject]  = ???  
val grouped = rep.groupBy { _.get[Int]("id") }
grouped.foldLeft(Seq.empty[JSONObject]) { case (acc, (_, seq)) =>
  val joinedJson = seq.foldLeft(JsonObject("feedback.attachments" -> JsonArray.empty)) {
    JsonObject.joinRight("feedback.attachments")
  }
  acc ++ Seq(joinedJson)
}

JsonObject should be able to ignore/keep null values

The default behaviour for now is to ignore null values. We should provide an alternative way and decide what should be a default strategy.

Probably the default strategy should be to keep null-values. But an alternative way is to skip them:

JsonObject.compact(...)

The JsonNull object from the commit 7755def should be restored.

It also would be nice to having a way of compatiing json object (removing null values). Like this:

val json = JsonObject("")
val c = json.compact

Facets might be composed with for-comprehension

I can't stop to use monads everywhere. Sorry.

val doAllTheMagic = for {
  http <- TurnJsonIntoHttp
  httpWithHeaders <- AddHeaders("asd", "asd")
} yield httpWithHeaders

service afterThat allTheMagic

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.