Play 2.1 - WS API - Missing Type Param Compile Error - WS.url(...).get().map { r => ... } - playframework-2.1

The error missing parameter type for response is given when I try to compile this code which comes (almost) directly from the Play 2.1 Docs
def feedTitle(feedUrl: String) = Action {
Async {
WS.url(feedUrl).get().map { response =>
Ok("test")
}
}
}
So then I give it a type like this, {response: WS.Response => ...} but then I get this error:
type mismatch;
found : play.libs.WS.Response => play.api.mvc.SimpleResult[String]
required: play.libs.F.Function[play.libs.WS.Response,?]

I think your imports are wrong. It should be play.api.libs.ws.WS instead of play.libs.WS.Response.
See http://www.playframework.com/documentation/api/2.1.0/scala/index.html#play.api.libs.ws.Response

My problem was that I imported play.libs.WS and not play.api.libs.ws.WS (notice the api package). I had to also import scala.concurrent.ExecutionContext.Implicits.global but the error message told me to do so, so that was simple.

Related

Share image from `expo assets` using expo-sharing produces mysterious error

I am using latest expo-47 with dev-client i have taken care of creating custom dev-client that includes the libraries that i am using on the given code.
So i will explain my case ( i am targeting android ) :
Inside the local expo assets i have 30 images
I want to allow the user to share the images using expo-sharing but i am getting error [ see end of post ]
Below is an example of many codes i have tried it just doesn't work :
import * as Sharing from 'expo-sharing'
async function shareImage(imageURI) {
try {
await Sharing.shareAsync(require('../../../assets/images/motivational/36.jpg'))
} catch (error) {
console.log(error)
}
}
The error is the below :
[Error: Argument of an incompatible class: class java.lang.Double cannot be passed as an argument to parameter expecting class java.lang.String.]
What is this supposed to mean ?
I HAVE of course verified that the image exists on the given path
Remove the require statement from .shareAsync.
Write it like this :
await Sharing.shareAsync('../../../assets/images/motivational/36.jpg')
-OR-
Define the path before hand and call it as
await Sharing.shareAsync(imageURI).
Let me know if this solves it.

Lumen 8 - Using Faker in tests makes InvalidArgumentException: Unknown format "name"

I'm using Lumen default Tests only added this line to the test :
$users = \App\Models\User::factory()->count(5)->create();
But i get this error when running the test :
InvalidArgumentException: Unknown format "name"
I did't touch the UserFactory Class i include it below , whats wrong with my code?
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
];
}
Should anybody else end up here looking for a similar issue in Laravel, make sure you include
parent::setUp();
in your setup method (if you have one). For example,
class ManageDocumentTest extends TestCase
{
public $user;
public function setUp():void
{
parent::setUp();
$this->user = User::factory()->create();
...
Uncommented these lines in app.php and its working now :
$app->withFacades();
$app->withEloquent();
You have to extend use Tests\TestCase instead of PHPUnit\Framework\TestCase.
At least, it helped me.
If you are using Tests\TestCase, calling parent::setUp(); and it still doesn't work, make sure not to call $faker before the actual test - ie. in a #dataProvider it won't work

GraphQL gql Syntax Error: Expected Name, found }

I'm attempting to set up Apollo GraphQL support in a new React project, but when I try to compile a query using gql I keep receiving the error:
Syntax Error: Expected Name, found }
This is generated by the following code:
import gql from 'graphql-tag'
const query = gql`
{
user(id: 5) {
firstName
lastName
}
}
`
console.log(query)
I'm basing this code off the example code found here: https://github.com/apollographql/graphql-tag
What is the Name referred to in the error message? Does anyone know what I'm doing wrong here?
This error occurs mostly when there are unclosed curly braces or when some fields are not properly defined while calling the query.
The accepted answer didn't solve my issue. Instead, it worked if you remove the initial curly brackets.
The query should look like this instead:
const query=gql`
user(id: 5) {
firstName
lastName
}
`
The causes could be:
you are adding a "()" at the beginning for no reason
you need to add more 'nested' parameters.
Especially if you are using an online GraphiQL editor. Examples:
1- Wrong code (extra parenthesis)
{
allFilms() {
films {
title
}
}
}
2- Wrong code (more parameters need it eg: title)
{
allFilms {
films {
}
}
}
3- Correct code
{
allFilms {
films {
title
}
}
}
GraphQLError: Syntax Error: Expected Name, found "$".
One more example of a similar error (For other users).
theErrorIsHere (Could be extra ( or { before the $varName) added before $speakerId
Error code:
const FEATURED_SPEAKER = gql`
mutation markFeatured($speakerId: ID!, $featured: Boolean!){
markFeatured(speaker_id: theErrorIsHere$speakerId , featured: $featured){
id
featured
}
}
`;
Correct code:
const FEATURED_SPEAKER = gql`
mutation markFeatured($speakerId: ID!, $featured: Boolean!){
markFeatured(speaker_id: $speakerId , featured: $featured){
id
featured
}
}
`;
I'm not 100% sure what the root of my problem was, but moving all the query code into a separate es6 module fixed the issue. There must have been some kind of contamination from the surrounding code. For reference my query was embedded within a React component.
This works:
import gql from 'graphql-tag'
const query = gql`
{
user(id: 5) {
firstName
lastName
}
}
`
export default query
Another cause for this error: you are referencing a type that is defined further down. Move the type you are referencing up.
For example:
type Launch {
rocket: Rocket
}
type Rocket {
name: String
}
will throw an error, as Launch references Rocket before Rocket is defined.
The corrected code:
type Rocket {
name: String
}
type Launch {
rocket: Rocket
}
In my case, I got the error simply because I'm adding : which I shouldn't have done.
e.g:
const query = `
query($id: String!) {
getUser(id: $id) {
user: {
id
name
email
createdAt
}
}
}
`
If you pay close attention to line 4 of the code above you'll realize that I added : after the user before the curly brace, then I began to list the user's data I wanna query and THAT WAS EXACTLY WHERE THE ERROR WAS!
Removing the : solve the issue!
It should be:
user {
id
name
...
}
In NestJS framework, this error happened to me because I defiled GraphQL field in my schema.graphql file as:
lastUpdated(): Date
Instead it should be just
lastUpdated: Date
(it doesn't take any argument)
I was receiving a similar error server side:
GraphQLError: Syntax Error: Expected Name, found ]
I realized the cause in my case was a type definition with an empty array.
This breaks:
type Settings {
requires: []
}
But this works:
type Settings {
requires: [String]
}
I had this problem and the cause was a string value with double-quotes inside double-quotes, like so: "this "is" bad".
In my case I got the error because of the following:
const GET_POSTS_OF_AUTHOR = gql`
query GetPostsOfAuthor($authorId: Int!) {
postsOf($authorId: Int!) {
id
title
}
}
`;
When it should have been:
const GET_POSTS_OF_AUTHOR = gql`
query GetPostsOfAuthor($authorId: Int!) {
postsOf(authorId: $authorId) {
id
title
}
}
`;
erroneously thought $authorId passed through identically to the function call instead of setting a property inside the function call.
This can happen if you use gql from #clinet/apollo and in the backticks you try to inject dynamic js value. Remove it and replace with normal scalar and it will fix your issue.
example:
${SOME_MAX_VALUE} -> 20
On ny side the error was caused by extra {} Curly braces. Solved by just removing them.
I was getting the same error. In my case putting the id inside double quote solved the issue as the type of id required string value.
{
product(id: "${id}") {
name
}
}
Posting here in case anyone else had this problem but you also get this error if you accidentally make your query look like json with colons (:).
ex:
data {
property {
key: {
deepKey
}
}
}
will give the same error from GQL compile

Http4s EntityDecoder not being auto derived for simple case class

I am getting this error:
Cannot decode into a value of type com.blah.rest.model.UserProfile,
because no EntityDecoder[cats.effect.IO, com.blah.rest.model.UserProfile]
instance could be found.
for the following case class:
case class UserProfile(id: Option[Int], firstName: String, lastName: String)
Encountered the error on POST code:
case req # POST -> Root / "v1" / "profiles" =>
req.as[UserProfile] flatMap {(up: UserProfile) =>
Ok(service.createProfile(up).asJson)
}
With the following POST body:
{
"firstName": "Jack",
"lastName": "Appleseed"
}
I think this happens when the body is being converted to UserProfile in req.as[UserProfile]!
But, this is a plain vanilla case class, the EntityDecoder should be auto-derived! I know akka-http does it!
Any ideas/suggestions?
Please Note: Http4sVersion = "0.18.0-M4" and circe version "0.9.0-M1"
The answer is:
req.decodeJson[UserProfile] flatMap {(up: UserProfile) =>
Ok(service.createProfile(up).asJson)
}
The reason you get that is the bridge from a Circe decoder to an http4s EntityDecoder is not implicit. You can make one if you're purely a JSON API, but that's not an assumption the library can generally make.
Adding this dependency:
"io.circe" %% "circe-generic" % "0.9.1"
resolved the auto-encoding of case classes to JSON for me.
It allows for the required import: import io.circe.generic.auto._

Option result in akka-http

I'm having an issue when trying to return an Option result from aka-http.
Basically it's a get that might have a 404.
pathPrefix("contacts" / Segment) { id =>
get {
contactService.getById(id).map {
case Some(c: ContactDto) => complete(OK -> toResource(c))
case None => complete(HttpResponse(NotFound))
}
}
}
Which gives me and error of:
[error] found : scala.concurrent.Future[akka.http.scaladsl.server.StandardRoute]
[error] required: akka.http.scaladsl.server.Route
[error] (which expands to) akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult]
[error] contactService.getById(id).map {
Any help would be greatly appreciated.
The problem you are seeing here has to do with the fact that you are using a Future and not because of the Option. I'm going to assume that the call contactService.getById(id) returns a Future. As the result of any route within your routing tree needs to be a Route (short for RequestContext => Future[RouteResult]) and your Future is itself not a Route, then you need to make a small change to handle this situation. You should be able to use the onComplete directive in combination with your Future as follows:
pathPrefix("contacts" / Segment) { id =>
get {
val fut = contactService.getById(id)
onComplete(fut){
case util.Success(Some(c: ContactDto)) =>
complete(OK -> toResource(c))
case util.Success(None) =>
complete(HttpResponse(NotFound))
case util.Failure(ex) =>
complete(HttpResponse(InternalServerError))
}
}
}
This code now handles the 3 possible outcomes from the Future (success with a Some, success with a None and a failure), producing a Route for each of those cases. This should fix your problem.
#cmbaxter's answer is correct but if you're happy with the standard status codes for the three cases above (Ok, NotFound, InternalServerError) then you can simplify the code to just complete directly with your function that returns Future[Option[T]].
pathPrefix("contacts" / Segment) { id =>
get {
complete(contactService.getById(id).map(toResource))
}
}
That is assuming that toResource returns a type where a ToEntityMarshaller exists for the type returned by that function. Akka provdes the machinery for Future and Option so you just need to supply the T part. For example if you were returning json and using spray-json then you can define a JsonWriter[T] and the implicits in akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport will do the rest. See spray-json-support.
The map(toResource) may not actually be required, but I'm assuming that does additional conversion of ContactDto to some other type - if its just converting it to json or similar then you can drop it and use the in built marshalling support as described above.