All Downloads are FREE. Search and download functionalities are using the official Maven repository.

lspace.decode.DecodeGraphQL.scala Maven / Gradle / Ivy

package lspace.decode

import java.util.UUID

import lspace._
import lspace.codec.ActiveContext
import lspace.codec.graphql.Decoder
import lspace.graphql.{Projection, Query}
import monix.eval.Task

trait DecodeGraphQL[A] extends Decode[A] {
  def decode: String => Task[A]
}

object DecodeGraphQL {
  def graphqlToQuery(allowedProperties: List[Property] = List(), forbiddenProperties: List[Property] = List())(
      implicit decoder: Decoder,
      activeContext: ActiveContext): DecodeGraphQL[Query] = {

    lazy val validProperty: Property => Boolean =
      if (allowedProperties.nonEmpty) { property: Property =>
        allowedProperties.contains(property) && !forbiddenProperties.contains(property)
      } else if (forbiddenProperties.nonEmpty) { property: Property =>
        !forbiddenProperties.contains(property)
      } else { property: Property =>
        true
      }

    lazy val validProjection: Projection => Boolean = (projection: Projection) =>
      validProperty(projection.property) && (projection.projections.isEmpty || projection.projections.exists(
        _.projections.forall(projection => validProjection(projection))))

    lazy val validQuery: Query => Boolean = (query: Query) => query.projections.forall(validProjection)

    if (allowedProperties.nonEmpty || forbiddenProperties.nonEmpty) {
      new DecodeGraphQL[Query] {
        def decode = { (graphql: String) =>
          decoder
            .toGraphQL(graphql) match {
            case query: Query =>
              if (validQuery(query)) Task.now(query)
              else Task.raiseError(new Exception("query contains certain properties which are not allowed"))
            case _ => Task.raiseError(new Exception("not a graphql query"))
          }
        }
      }
    } else
      new DecodeGraphQL[Query] {
        def decode = { (graphql: String) =>
          decoder
            .toGraphQL(graphql) match {
            case query: Query => Task.now(query)
            case _            => Task.raiseError(new Exception("not a graphql query"))
          }
        }
      }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy