Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
bengraygh
@bengraygh

Another way to phrase this might be: Is there a type I can import from sangria-relay that encompasses an ObjectType that conforms to a Node type?

I also have this problem. If you found a solution, I'm interested to hear it. Without defining everything in the same SchemaDefinition as one file, I get this problem.

André Schmidt
@ASchmidt84
HI. I have a question about a mutator. In the mutator I have an parameter. And if the submitter submit wrong data for the datatype (like two chars only lower case allowed an the submitter sends in uppercase or so) the error is very low like this {"name":"Exception","detail":""}
I have an deriveInputObjectType for my case class ADT. How I can offer a more detailed exception message for wrong parameters?
bengraygh
@bengraygh
Are you relying on the info coming to your client? You could see the exception thrown on the terminal of your JVM couldn't you? Or do you mean that you want more detail in the string given to the client?
André Schmidt
@ASchmidt84
I want a better exception description to the client
bengraygh
@bengraygh

I want a better exception description to the client

Ok, so you could define your own user facing error and pass that through to the client. The docs on the sangria site (which is down with a temporary mirror) show how to do this: https://sangria.netlify.app/learn/#custom-exceptionhandler

fjl716
@fjl716
Don't have access to https://sangria-graphql.org/
André Schmidt
@ASchmidt84
@bengraygh thank you. So i hope the docs will be on near
Erik
@erikdstock
So sangria's generated schema.graphql does not include the declaration scalar Long even though a special Long type is built in to the library. This breaks stitching into other schemas without manually adding a scalar Long after the fact. Is there a way to make sure this is included? I tried ham-fistedly adding it as a public member in my schema definition with simply val ImportedLong = sangria.schema.LongType but this doesn't change the output.
Erik
@erikdstock
My current approach is to do this in my writeSchema task:
object SchemaWriter extends App {
  implicit val ec = scala.concurrent.ExecutionContext.global

  val renderedStr = SchemaRenderer.renderSchema(SchemaDefinition().schema)
  val fileName = "src/main/resources/rendered.graphql"
  val pw = new PrintWriter(new File(fileName))
  pw.write("""
      |# Type not included by sangria's SchemaRenderer
      |scalar Long
      |
      |""".stripMargin)
  pw.write(renderedStr)
  pw.close()

  println(s"GraphQL SDL file written to `$fileName`.")
}
mynameistechie
@mynameistechie

Hiring Alert

Hey All,
We're hiring for Java Developer with GraphQL at Dallas,TX.If you're interested do connect with me to know more about this opportunity https://www.linkedin.com/in/karnala-harish-harry/ ASAP
(Sorry if this post not allowed but i want to help jobseekers)
André Schmidt
@ASchmidt84

I have a problem with en Enum (by enumeratum) and the graphql EnumType. The problem is on a mutation query. An Argument is a class Manager with contains an Enum. Always get an error:

Argument 'manager' has invalid value: At path '/role': error.sealed.trait (line 2, column 55):\n    addManager (vendorNumber: $vendorNumber, manager: $manager)

At role the Enum DefaultRoles is sitting.
I have an encode and a decoder:

implicit val ChargeTypeEncoder: Encoder[DefaultRoles] = new Encoder[DefaultRoles] {
    override def apply(enum: DefaultRoles): Json = stringEncoder.apply(enum.entryName)
  }

  implicit val ChargeTypeDecoder: Decoder[DefaultRoles] = new Decoder[DefaultRoles] {
    final def apply(c: HCursor): Result[DefaultRoles] = stringDecoder.apply(c).flatMap { s =>
      val maybeMember = DefaultRoles.withNameOption(s)
      maybeMember match {
        case Some(member) => Right(member)
        case _ => Left(DecodingFailure(s"$s' is not a member of enum $DefaultRolesType", c.history))
      }
    }
  }
André Schmidt
@ASchmidt84
I found out the problem is not at the marshalling. I have a mutation trait with an argument Manager. But I getting still this error: Argument 'manager' has invalid value: At path '/role': error.sealed.trait (line 2, column 55):\n addManager (vendorNumber: $vendorNumber, manager: $manager)
Encoding and decoding works fine!
val MutationType = deriveContextObjectType[FulfillerGraphQLSecureContext,FulfillerGraphQLMutation,Unit](_.mutation)

  val FulfillerSchema = Schema(Query,Some(MutationType))
This ist my schema and my trait has this method: @GraphQLField def addManager(vendorNumber: String, manager: Manager): Future[FulfillerView]
André Schmidt
@ASchmidt84
It seemes that the enumtype is not recognize as valid inputtype
André Schmidt
@ASchmidt84
Okay for all who running in same issue. The problem is very simple. It is the JSON dervied.oformat() which makes a object. But in graphql it is a string. To correct this, refactor it and create a dedicated way with JSON and graphql convertig let works fine.
implicit val defaultRolesWrites: Writes[DefaultRoles] = {r => Json.toJson(r.name) }
  implicit val defaultRolesReads: Reads[DefaultRoles] = Reads{
    case JsString(j) =>
      DefaultRoles.withNameInsensitiveOption(j).map{r => JsSuccess(r)}.getOrElse(JsError("String value not accepted"))
    case _ => JsError("String value expected")
  }
  implicit val defaultRolesFormat: Format[DefaultRoles] = Format(defaultRolesReads,defaultRolesWrites)
  implicit val DefaultRolesType = new schema.EnumType[DefaultRoles](
    name = "DefaultRoles",
    description = Some("A enum role type. Describes a special role"),
    values = List(
      schema.EnumValue[DefaultRoles](
        name = "FulfillerPresidentRole",
        description = Some("Fulfiller president role - means owner of the fulfiller"),
        value = DefaultRoles.FulfillerPresidentRole
      ),
      schema.EnumValue(
        name = "FulfillerCEOManagerRole",
        description = Some("Fulfiller CEO role"),
        value = DefaultRoles.FulfillerCEOManagerRole
      ),
      schema.EnumValue(
        name = "FulfillerArticleManagerRole",
        description = Some("Fulfiller article manager role - only responsible for articles of the fulfiller"),
        value = DefaultRoles.FulfillerArticleManagerRole
      ),
      schema.EnumValue(
        name = "FulfillerInvoiceManagerRole",
        description = Some("Fulfiller invoice manager role - only responsible for invoice and all relating topics"),
        value = DefaultRoles.FulfillerInvoiceManagerRole
      ),
      schema.EnumValue(
        name = "UserRole",
        description = Some("Simple user role"),
        value = DefaultRoles.UserRole
      )
    )
  ){
    override def coerceUserInput(value: Any): Either[Violation, (DefaultRoles, Boolean)] = value match {
      case valueName: String =>
        DefaultRoles.values
          .find(_.getClass.getSimpleName.startsWith(valueName))
          .map(r => Right(r -> false))
          .getOrElse(
            DefaultRoles
              .withNameInsensitiveOption(valueName)
              .map(r => Right(r -> false))
              .getOrElse( Left(EnumValueCoercionViolation(valueName, name, values.map(_.name)) ) )
          )

      //        Right(FulfillerCEOManagerRole -> false)
      //        DefaultRoles.withNameInsensitiveOption(valueName).map(r => Right(r -> false)).getOrElse( Left(EnumValueCoercionViolation(valueName, name, values.map(_.name)) ) )
      //      case v if byValue exists (_._1 == v) => Right(v.asInstanceOf[T] -> byValue(v.asInstanceOf[T]).deprecationReason.isDefined)
      case _ => Left(EnumCoercionViolation)
    }

    override def coerceInput(value: ast.Value): Either[Violation, (DefaultRoles, Boolean)] = value match {
      case ast.EnumValue(valueName, _, _) =>
        DefaultRoles.values
          .find(_.getClass.getSimpleName.startsWith(valueName))
          .map(r => Right(r -> false))
          .getOrElse(
            DefaultRoles
              .withNameInsensitiveOption(valueName)
              .map(r => Right(r -> false))
              .getOrElse( Left(EnumValueCoercionViolation(valueName, name, values.map(_.name)) ) )
          )
      case _ => Left(EnumCoercionViolation)
    }

    override def coerceOutput(value: DefaultRoles): String = value.name
  }
Anas H. Albarghouthy (Anas Barg)
@anasbarg

Hi, I have this code

val sangriaSchema =
    Schema.buildFromAst(apiSchemaGenerator.buildApiSchemaAsDocument)

val violations = QueryValidator.default
      .validateQuery(sangriaSchema, query)
      .toList

The problem is that violation is always an empty list, even when there are violations in the query.

Dan Di Spaltro
@dispalt
@schleumer did you ever figure out that bug with PossibleObject in 2.13?
Horacio
@krabbit93
Hello, I have tried to create a custom NonEmptyListInputType, but i can't yet. I tried using a custom ValidationRule, How can make that?
Pawel
@odwrotnie
Hello!
Are you able to connect Sangria to existing database with auto schema generation?
Ririshi
@Ririshi
Hi everyone, I'm totally new to both Scala and Sangria, and I'm using Sangria in a Play application to create a GraphQL API for our frontend to interface with. I'm using MongoDB as our data storage and am a bit stuck on creating relationships between different models. I currently have a Story case class and an Author case class, and created simple queries for both models to add, find, and update some documents in the MongoDB database. My issue now is with the ability to subquery the author of a story, or the stories written by an author...
Ririshi
@Ririshi

I tried following this tutorial:
https://medium.com/@toxicafunk/graphql-subqueries-with-sangria-735b13b0cfff

But the ids.flatMap(id => ctx.execution.course(id)) part gives me an error that the overloaded flatMap cannot be resolved. I'm using reactivemongo.api.bson.BSONObjectID as Id type, and it seems like there is no flatMap available for a Seq[BSONObjectID]

Greg Fisher
@gnfisher
Hello, it appears that deriveObjectType would convert a Left(error) into a 500 response? Is that accurate?
Yann Simon
@yanns
Are you using sangria with scala 2.11? If yes, please comment: sangria-graphql/sangria#523
Andrii Zarichnyi
@azarichnyi
Good day, people! Sorry, for maybe dummy question, but googling didn’t help. Does Sangria support interfaces that implement interfaces?
3 replies
sinanspd
@sinanspd
ignore my last message... I didn't realize I was in the sangria channel. My bad ... 🤗
Nick Hudkins
@nickhudkins
Hey @yanns , I'd love to help out even if it is just with issue triage for Sangria. Feel free to reach out to me over email if you want to connect (or here!)
4 replies
Yann Simon
@yanns
Hi if someone is looking for something easy to help, we would need this kind of change for all repositories where we release binaries: sangria-graphql/sangria-circe#37
That way we are sure that we emit jvm 8 bytecode.
2 replies
Nick Hudkins
@nickhudkins
Hey @yanns do you have a good list of the official repos now? I know we had to split off for a bit. Happy to spend some time cleaning up
Yann Simon
@yanns
Nick Hudkins
@nickhudkins
Wonderful :), I've got a couple of PRs that I am cleaning up for sangria at the moment, just some bug fixes, and then I can tackle the jvm bytecode stuff.
I'd love to co-ordinate with the maintainers and get a plan together if possible. Even to just make a decision on "Should we support 2.11" etc...
Nick Hudkins
@nickhudkins
Screen Shot 2020-10-22 at 1.21.34 PM.png
Oliver Wetterau
@owetterau
@mkotsur Did you solve your problem with deriveInputObjectType/ deriveEnumTypeissue? I have the same problem ("invalid value: CNil") and am using Circe, too...
Miklos Szots
@smiklos
Hi all,
Recently we've been introducing some bugs in our api when sangira types and circe types don't align. There's this strange duality between those types like enums and scalar aliases that both need to be mapped for sangria and circe. Is there a better approach for this? Can't sangria derive or reuse the circe encoders or the other way around?
Dan Di Spaltro
@dispalt
im not the author but have used it extensively and this is the biggest shortcoming of sangria @smiklos
Nick Hudkins
@nickhudkins
Hey @smiklos and @dispalt sangria by itself has no "allegiance" to any JSON library. I am not sure that I follow what the situation is when your GraphQL types and Circe types don't align. Could you provide a simplified test case to show the behavior and help us understand what you'd be looking for?
Specifically, all things "Circe" and Sangria are handled within the sangria-circe package here: https://github.com/sangria-graphql/sangria-circe and the purpose of the library is only to provide marshalling and unmarshalling of GraphQL types as the schema is being materialized, or input is received.
Miklos Szots
@smiklos
Basically, the sangria-circe module parses json into an AST. This is great, and I understand that this is modular so one can use another marshaller like jackson or so.
The problem arises from the fact that all circe usage is two step, marshalling and encoding the result of the AST into a case class hierarchy.
It's this encoding that doesn't align with Sangria types. I need to both define a case object hierarchy as an enumtype so sangria renders it properly, but I also should not foget to create a circe derivation out of it so case classes can be generated. Lacking that, sangria will validate/parse the json but will crash when case classes are to be created
If I tell Circe how to encode/decode my enum/value class or whatever, I don't feel I should repeate this to Sangria as well. I'ts already done once for circe
the issue is mostly prominent with strong typing (newtype/ extends anyval) because there you need to create a scalar alias for sangria to understand that it's not a nested field (the value in the anyval) but just a regular top level field. Then you need to tell circe how to encode/decode this as well. Same for enums
Nick Hudkins
@nickhudkins
Have an example I can take a look at?
Or, any chance you could fork: https://github.com/sangria-graphql/sangria-akka-http-example and recreate the issue? The only time Circe and Sangria "interact" is when it is being materialized. Are you using Json WITHIN your resolvers?
Miklos Szots
@smiklos
Here is one
case class ResultData(resultId: ResultId)

object ResultId {

  //Already derived it as a string
  //This is a factory for creating ResultId from String
  implicit val encoder: Encoder[ResultId] = Encoder.encodeString.contramap(_.id)
  implicit val decoder: Decoder[ResultId] = Decoder.decodeString.map(ResultId(_))

  //Now I repeat myself
  //This is also a factory for creating ResultId from String
  implicit val graphQlType = ScalarAlias[ResultId, String](
    StringType,
    _.id,
    id => Right(ResultId(id))
  )
}

case class ResultId(id: String) extends AnyVal
Nick Hudkins
@nickhudkins
Ah, ok, so you would hope that by defining the ScalarAlias, that you'd get your encoder / decoders for whatever marshalling library you're using correct?
Miklos Szots
@smiklos
well, that would be ideal isn't it. Not whatever, I'm more than happy if it only supports circe (;> )
Nick Hudkins
@nickhudkins
Haha :) ok, let me give some thought to that.
Miklos Szots
@smiklos
We could possibly create a conversion from sangria type to circe or the other way around. The tricky thing in both cases is that both sangria and circe is more than happy to compile when using auto derivation without any of these extra implicits. a bit better solution would be to be able to derive one of the encoder/decoder pairs from the other. A lot better solution would be when sangria generates marshaller, it would auto derive circe encoders