hotchocolate throws error when using UseFiltering() on a field - graphql

I have a pretty simple setyp where I'm putting graphql over an entityframework datacontext (sql server).
I'm trying to get filtering to work. I've tried adding .UseFiltering() to a field descriptor like so...
descriptor.Field(t => t.AccountName).Type<NonNullType<StringType>>().UseFiltering();
But it causes this error on startup...
HotChocolate.SchemaException: 'Unable to infer or resolve a schema
type from the type reference Input: System.Char.'
I assume I'm doing something wrong somewhere...

"UseFiltering" is supposed to be used to filter data which represents a collection of items in some way (IQueryable, IEnumerable, etc).
For instance, if you have users collection and each user has AccountName property you could filter that collection by AccountName:
[ExtendObjectType(Name = "Query")]
public class UserQuery
{
[UseFiltering]
public async Task<IEnumerable<User>> GetUsers([Service]usersRepo)
{
IQueryable<User> users = usersRepo.GetUsersQueryable();
}
}
In that example the HotChocolate implementation of filtering will generate a number of filters by user fields which you can use in the following way:
users(where: {AND: [{accountName_starts_with: "Tech"}, {accountName_not_ends_with: "Test"}]})
According to your example: the system thinks that AccountName is a collection, so tries to build filtering across the chars the AccountName consists of.

Related

OData EDM model - auto-expanding a nested Entity Type

I'm using OData v4 and the models are configured with the EdmModel Builder for our .NET Web API.
I have two models defined like this:
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string Category { get; set; }
public Customer OrderCustomer { get; set;}
}
These models have corresponding controllers and are registered as follows:
builder.EntitySet<Customer>("Customers")
.EntityType
.HasKey(x => x.CustomerId);
builder.EntitySet<Order>("Orders")
.EntityType
.HasKey(x => x.OrderId)
.Expand(
maxDepth: 2,
expandType: SelectExpandType.Automatic,
properties: nameof(Order.OrderCustomer));
I'm able to make OData requests to both these endpoints as follows:
/Customers/{Id} and
/Orders/{Id}.
I'm expecting that when I query the Orders, the nested EntitySet Customers will auto expand since I've set expandType: SelectExpandType.Automatic on the Order EntitySet. However, I can't get the CustomerOrder property to auto-expand on the Customer and I have to call the request with an expand parameter:
/Orders/{Id}?$expand=OrderCustomer.
I think this is because both Customer and Order are registered as EntitySets, so OData expects that an expand parameter be provided if they are nested. Is there a way to get the OrderCustomer property to auto-expand (i.e. without the need for the expand parameter to be provided)? My understanding of OData/ Edm Models is pretty elementary so any help is appreciated.
Your fluent configuration is correct, for OData v4, that will work for both collection and item queries.
If it is not working for you there are 3 possible issues:
You do not appear to be using the OData v4 URL convention for item queries, in v4 the expected URL is:
/Orders({Id})
This brings into question how you modified the router to support the v3 syntax, there are multiple variation on how to implement the v3 routes so it is possible that changes made in this area could affect the way that default expansion and selection is applied, or if it should apply.
You may not be including the navigation data in your data query. If the data is not retrieved from the data store, then it stands to reason that it will not be in the output recordset. If you are manually using the ODataQueryOptions.ApplyTo() to apply the user request to your query, then this will not take into account the configuration on the model, it will only apply thequery options that the caller has specified.
The caller might be specifying an Empty $expand= which will cancel out the auto configuration. Even if the originating caller has not specified any query options it is common enough for OData APIs to have standard or custom middleware running that might be manipulating the request query strings. To verify the URL is untampered, log it in your GET method handler and make sure the $expand is not specified.
As with the previous point, the ODataQueryOptions parameter in your GET method should NOT show any value for the SelectExpand if you want the auto configuration to be applied.
Finally, the last place to check is that you haven't overriden the default EnableQueryAttribute. If you have implemented your own custom implementation of EnableQueryAttribute then make sure that you still call the base implementation to correctly apply the ODataQueryOptions AND the schema defaults to the underlying IQueryable result.
In addition to the answer provided by Chris Schaller.
Another issue I had was caused by the casing on the property. For example, I have camelCasing enabled on the builder
builder.EnableLowerCamelCase();
This means the naming in the Expand on the configuration needed to be updated to match.
.Expand(
maxDepth: 2,
expandType: SelectExpandType.Automatic,
properties: "orderCustomer"); // <-- camelCase
This seems to be required even if EnablePropertyNameCaseInsensitive is enabled in the ODataOptions.

Multiple field resolver resolves same rest API with different query parameters

We are planning to use graphql for orchestrations (For e.g. UI client invokes graphql service which goes to multiple rest endpoint and return the result). Problem here is from one rest endpoint we have to pass different types of query parameters based on the field requested by our client.
We use spring-boot-graphql and graphql-java-tools libraries to initialize graphql
type Query{
user(id: ID): User
}
type User{
phone: [Phone]
address: [Address]
}
type Phone{...}
type Address{...}
My code resolves user field and invoke rest endpoint to fetch phone and address information in a single call like
https:restservice.com\v1\user\123?fields=phone,address
How to resolve two fields expecting data from same rest service. I want something like when client request for phone then i needs to send fields in request parameters as phone alone without address. Can we do that? or is there any other way to define schema to solves this problem?
query {
user(userId : "xyz") {
name
age
weight
friends {
name
}
}
}
Knowing the field selection set can help make DataFetchers more efficient. For example in the above query imagine that the user field is backed by an SQL database system. The data fetcher could look ahead into the field selection set and use different queries because it knows the caller wants friend information as well as user information.
DataFetcher smartUserDF = new DataFetcher() {
#Override
public Object get(DataFetchingEnvironment env) {
String userId = env.getArgument("userId");
DataFetchingFieldSelectionSet selectionSet = env.getSelectionSet();
if (selectionSet.contains("user/*")) {
return getUserAndTheirFriends(userId);
} else {
return getUser(userId);
}
}
};
https://www.graphql-java.com/documentation/v12/fieldselection/

Error on GraphQL : no provided id but the store already contains an id of

I am very new to GraphQL and Apollo, and I don't understand what is wrong with the 'aliasEmail' field below. When I add this one to the query, I get this error message. When I remove it from the query, everything works perfectly.
It is well defined in 'types.graphql' and is just a simple string field.
index.js:2178 Unhandled (in react apollo:Apollo(withRouter(EmailSettingsContainer))) Error: Network
error: Error writing result to store for query:
query getCompanyForAliasEmailEditForm($companyId: ID) {
Company(id: $companyId) {
name
isTaxActive
telFixe
aliasEmail
telMobile
__typename
}
}
Store error: the application attempted to write an object with no
provided id but the store already contains an id of
Company:cje6xkcnxl83u01353a20p1t6 for this object. The selectionSet
that was trying to be written is:
Company(id: $companyId) {
name
isTaxActive
telFixe
aliasEmail
telMobile
__typename
}
It sounds like there's already another query being made elsewhere in the app that also returns the Company object and that query includes the id (or _id) field, while the query in this case does not. Apollo uses both the typename and id to generate the cache key for your query result (unless dataIdFromObject is used to modify this behavior), and so throws an error when it detects the above discrepancy. Try including the id field in your getCompanyForAliasEmailEditForm query.

AutoMapper Project().To() not working for interface destination

I have a situation in AutoMapper where I need to create a mapping with an interface destination. This is not a problem, and when using the normal Mapper.Map, it returns a proxy class as expected. However, when I try to do something similar with .Project().To(), which I need to use because an ORM is involved, I have issues. Here is the exact code that is failing which I replicated in a unit test:
AutoMapper.Mapper.CreateMap<RoleDto, IRole>(); //both just have Id/Name
IQueryable<RoleDto> roleDtos = new List<RoleDto>
{
new RoleDto { Id = 1, Name = "Role1" },
new RoleDto { Id = 2, Name = "Role2" }
}.AsQueryable();
//this works:
List<IRole> roles = roleDtos.Select(
roleDto => AutoMapper.Mapper.Map<IRole>(roleDto)
).ToList();
//this does not work:
List<IRole> roles2 = roleDtos.Project().To<IRole>().ToList();
I'm getting ArgumentException:
ArgumentException: Type 'UnitTestProject5.IRole' does not have a default constructor
In my real implementation the .Select is being performed on an Entity Framework collection, which is why I need to stick with .Project().To().
I have no issues with .Project().To() if the destination is not an interface. Additionally, I have no issues with the interface destination if I use .Map().
How can I get the interface destination and .Project.To() to work at the same time? Why is .Project.To() not giving me proxy classes like .Map() is? Any ideas?
Thanks!
Mapper.Map() takes the linq-to-objects route to materialize objects. As you said, AutoMapper is capable of creating types on the fly if the mapped target is an interface.
Project().To() is a way to translate the whole query, including the mapping, into SQL. Which is great, because only the properties that are required for the target object are included in the SQL query. However, the things AutoMapper does for creating types on the fly (undoubtedly some Refection voodoo) can never be part of an expression tree that can be converted into SQL. That's why Project.To simply tries to new up an object, even if it's an interface.
You'll have to use a concrete type as a mapping target. Of course, this type can implement an interface, so you can keep the independence you want.

How can I create a LINQ view?

My team is using Entity Framework 4.3.0 - Code Only with POCO classes as our ORM. Right now we use DBSets of Classes to access our 'tables'
Public Property Customers As DbSet(Of Customers)
But often we are doing soft deletes based on a IsDeleted column in LINQ, and filtering our select statements accordingly:
Dim LiveCustomers =
From C In EM.Customers
Where C.DeleteFlag = False
What I would really like to do is, instead of writing every query to include this filter, create some lower level property (possibly at our inherited DbContext level) that provides the filtered set, while maintaining strong type.
I tried this:
Public Property Customers As DbSet(Of Customer)
Public Property Customers_Live As DbSet(Of Customer)
Get
Return From C In Customers
Where C.DeleteFlag = False
End Get
Set(value As DbSet(Of Customer))
Customers = value
End Set
End Property
However that yielded me this error:
Multiple object sets per type are not supported. The object sets 'Customers' and 'Customers_Live' can both contain instances of type '__.Customer'.
A quick check on google yielded this promising result (How to: Query Objects with Multiple Entity Sets per Type) But after updating my Connection String, I'm still getting the same error.
<add name="EntityManager"
providerName="System.Data.SqlClient"
connectionString="
Data Source=xxxxxx;
Initial Catalog=xxxxxx;
User Id=xxxxxx;
Password=xxxxxx;
MultipleActiveResultSets=True"/>
So my question is, how could I effectively create a LINQ view that allows me to apply filtering, without impacting the upstream usage too drastically?
Change your property like this:
Public Property Customers As DbSet(Of Customer)
Public Property Customers_Live As IQueryable(Of Customer)
Get
Return From C In Customers
Where C.DeleteFlag = False
End Get
End Property
This is slightly different, as you won't have things like Add() or Remove(), but for a view you typically wouldn't expect to have that kind of functionality. If you want to add a new one, or remove one you should use the normal Customers property.
You could have your POCO classes inherit from a new class that has a new method that would do the filtering for you. Add something like this to the new class
--PSEUDO CODE!--
Public Function Filtered() as IEnumerable(Of Out T)
Return (From x In Me Where x.DeleteFlag).ToList()
End Function
and you could call it like:
Dim LiveCustomers =
From C In EM.Customers.Filtered
Or you could create an Interface and do a dependancy injection when you call your linq query. You'll have to google that one :)

Resources