Skip to content

Commit

Permalink
Merge branch 'main' into mst/isselected-improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelstaib committed Apr 16, 2024
2 parents 30e69a1 + 38de4ac commit a2c1f1a
Show file tree
Hide file tree
Showing 10 changed files with 115 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,26 @@ private static void CreateMutationType(OpenApiWrapperContext context)
description += $"\n\nReturns: {responseDescription}";
}

var payloadType = context.OperationPayloadTypeLookup[operation.Value.OperationId];

var outputField = new OutputField(GetFieldName(operation.Value.OperationId))
{
Description = description,
Type = context.OperationPayloadTypeLookup[operation.Value.OperationId],
Type = IsPayloadTypeNullable(operation.Value)
? payloadType
: new NonNullType(payloadType),
};

if (operation.Value.Parameters.Count > 0 || operation.Value.RequestBody is not null)
{
var inputField = new InputField(
OpenApiResources.InputField,
context.OperationInputTypeLookup[operation.Value.OperationId])
var inputType = context.OperationInputTypeLookup[operation.Value.OperationId];

var inputField = new InputField(OpenApiResources.InputField)
{
Description = operation.Value.RequestBody?.Description,
Type = IsInputTypeNullable(operation.Value)
? inputType
: new NonNullType(inputType),
};
outputField.Arguments.Add(inputField);
}
Expand All @@ -61,4 +68,16 @@ private static void CreateMutationType(OpenApiWrapperContext context)

context.MutableSchema.MutationType = mutationType;
}

private static bool IsPayloadTypeNullable(Operation operation)
{
return operation.Response?.Content.Values.FirstOrDefault()?.Schema.Nullable == true;
}

private static bool IsInputTypeNullable(Operation operation)
{
return
operation.Parameters.Count == 0 &&
operation.RequestBody?.Content.Values.FirstOrDefault()?.Schema.Nullable == true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ private static void CreateQueryType(OpenApiWrapperContext context)
}

var typeInfo = context.GetSchemaTypeInfo(schema);
var type = typeInfo.GetGraphQLTypeNode(false);
var type = typeInfo.GetGraphQLTypeNode();

var description = operation.Value.Description;

Expand Down Expand Up @@ -73,7 +73,7 @@ private static void CreateQueryType(OpenApiWrapperContext context)
{
var typeInfo = context.GetSchemaTypeInfo(parameter.Schema);
outputField.Arguments.Add(
new InputField(parameter.Name, typeInfo.GetGraphQLTypeNode(false))
new InputField(parameter.Name, typeInfo.GetGraphQLTypeNode(parameter.Required))
{
Description = parameter.Description,
});
Expand All @@ -83,7 +83,8 @@ private static void CreateQueryType(OpenApiWrapperContext context)
requestBody.Content.FirstOrDefault().Value.Schema is {} schema)
{
var typeInfo = context.GetSchemaTypeInfo(schema);
outputField.Arguments.Add(new InputField("value", typeInfo.GetGraphQLTypeNode(false)));
outputField.Arguments.Add(
new InputField("value", typeInfo.GetGraphQLTypeNode(requestBody.Required)));
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Text.Json;
using HotChocolate.Execution.Configuration;
using HotChocolate.Language;
using HotChocolate.Resolvers;
using HotChocolate.Skimmed;
using HotChocolate.Types;
Expand All @@ -10,7 +9,6 @@
using IField = HotChocolate.Skimmed.IField;
using InputObjectType = HotChocolate.Skimmed.InputObjectType;
using ObjectType = HotChocolate.Skimmed.ObjectType;
using TypeKind = HotChocolate.Skimmed.TypeKind;

namespace HotChocolate.OpenApi;

Expand Down Expand Up @@ -77,7 +75,7 @@ public static class RequestExecutorBuilderExtension
fieldDescriptor.Argument(
fieldArgument.Name,
descriptor => descriptor
.Type(new NamedTypeNode(fieldArgument.Type.NamedType().Name))
.Type(fieldArgument.Type.ToTypeNode())
.Description(fieldArgument.Description));
}
Expand All @@ -98,13 +96,9 @@ public static class RequestExecutorBuilderExtension

private static IObjectFieldDescriptor CreateFieldDescriptor(IField field, IObjectTypeDescriptor desc)
{
ITypeNode baseType = field.Type.Kind == TypeKind.NonNull
? new NonNullTypeNode(new NamedTypeNode(field.Type.NamedType().Name))
: new NamedTypeNode(field.Type.NamedType().Name);

var fieldDescriptor = desc.Field(field.Name)
.Description(field.Description)
.Type(field.Type.Kind == TypeKind.List ? new ListTypeNode(baseType) : baseType);
.Type(field.Type.ToTypeNode());

return fieldDescriptor;
}
Expand All @@ -117,15 +111,9 @@ private static IObjectFieldDescriptor CreateFieldDescriptor(IField field, IObjec
foreach (var field in skimmedType.Fields)
{
ITypeNode baseType = field.Type.Kind == TypeKind.NonNull
? new NonNullTypeNode(new NamedTypeNode(field.Type.NamedType().Name))
: new NamedTypeNode(field.Type.NamedType().Name);
desc.Field(field.Name)
.Description(field.Description)
.Type(field.Type.Kind == TypeKind.List
? new ListTypeNode(baseType)
: baseType);
.Type(field.Type.ToTypeNode());
}
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public SchemaTypeInfo(OpenApiSchema schema)
GraphQLTypeName = GetGraphQLTypeName(TypeName, Format);
IsScalar = Scalars.IsBuiltIn(GraphQLTypeName);
}

/// <summary>
/// The schema the information is based on
/// </summary>
Expand Down Expand Up @@ -69,16 +69,24 @@ public SchemaTypeInfo(OpenApiSchema schema)
/// </summary>
/// <param name="required"></param>
/// <returns></returns>
public IType GetGraphQLTypeNode(bool required)
public IType GetGraphQLTypeNode(bool required = true)
{
var unwrappedType = new ObjectType(GraphQLTypeName);
IType baseType = required
? new NonNullType(unwrappedType)
: unwrappedType;

return IsListType
? new ListType(baseType)
: baseType;
if (!IsListType)
{
return required && !Schema.Nullable
? new NonNullType(unwrappedType)
: unwrappedType;
}

IType elementType = Schema.Items.Nullable
? unwrappedType
: new NonNullType(unwrappedType);

return required && !Schema.Nullable
? new NonNullType(new ListType(elementType))
: new ListType(elementType);
}

private static string GetGraphQLTypeName(string openApiSchemaTypeName, string? format)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ type Mutation {
Returns: pet response
"""
addPet("Pet to add to the store" input: AddPetInput): AddPetPayload
addPet("Pet to add to the store" input: AddPetInput!): AddPetPayload!
"""
deletes a single pet based on the ID supplied
Returns: pet deleted
"""
deletePet(input: DeletePetInput): DeletePetPayload
deletePet(input: DeletePetInput!): DeletePetPayload!
}

type Pet {
Expand All @@ -40,7 +40,7 @@ type Query {
Returns: pet response
"""
findPetById("ID of pet to fetch" id: Long): Pet
findPetById("ID of pet to fetch" id: Long!): Pet!
"""
Returns all pets from the system that the user has access to
Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
Expand All @@ -50,7 +50,7 @@ type Query {
Returns: pet response
"""
findPets("maximum number of results to return" limit: Int "tags to filter by" tags: String): [Pet]
findPets("maximum number of results to return" limit: Int "tags to filter by" tags: [String!]): [Pet!]!
}

input AddPetInput {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type Query {
Returns: pet response
"""
findPetById("ID of pet to fetch" id: Long): Pet
findPetById("ID of pet to fetch" id: Long!): Pet!
"""
Returns all pets from the system that the user has access to
Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
Expand All @@ -19,7 +19,7 @@ type Query {
Returns: pet response
"""
findPets("maximum number of results to return" limit: Int "tags to filter by" tags: [String]): [Pet]
findPets("maximum number of results to return" limit: Int "tags to filter by" tags: [String!]): [Pet!]!
}

type Mutation {
Expand All @@ -28,13 +28,13 @@ type Mutation {
Returns: pet response
"""
addPet("Pet to add to the store" input: AddPetInput): AddPetPayload
addPet("Pet to add to the store" input: AddPetInput!): AddPetPayload!
"""
deletes a single pet based on the ID supplied
Returns: pet deleted
"""
deletePet(input: DeletePetInput): DeletePetPayload
deletePet(input: DeletePetInput!): DeletePetPayload!
}

type AddPetPayload {
Expand Down
6 changes: 0 additions & 6 deletions src/StrawberryShake/Client/src/Core/RequestStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,4 @@ public enum RequestStrategy
/// An id is send representing the query that is stored on the server.
/// </summary>
PersistedQuery,

/// <summary>
/// The full GraphQL query is only send if the server has not yet stored the
/// persisted query.
/// </summary>
AutomaticPersistedQuery,
}
26 changes: 17 additions & 9 deletions src/StrawberryShake/Client/src/Transport.Http/HttpConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,7 @@ public IAsyncEnumerable<Response<JsonDocument>> ExecuteAsync(OperationRequest re

private static GraphQLHttpRequest MapRequest(OperationRequest request)
{
var (id, name, document, variables, extensions, _, files, _) = request;

#if NETSTANDARD2_0
var body = Encoding.UTF8.GetString(document.Body.ToArray());
#else
var body = Encoding.UTF8.GetString(document.Body);
#endif
var (id, name, document, variables, extensions, _, files, strategy) = request;

var hasFiles = files is { Count: > 0, };

Expand All @@ -39,8 +33,22 @@ private static GraphQLHttpRequest MapRequest(OperationRequest request)
variables = MapFilesToVariables(variables, files!);
}

var operation =
new HotChocolate.Transport.OperationRequest(body, id, name, variables, extensions);
HotChocolate.Transport.OperationRequest operation;

if (strategy == RequestStrategy.PersistedQuery)
{
operation = new HotChocolate.Transport.OperationRequest(null, id, name, variables, extensions);
}
else
{
#if NETSTANDARD2_0
var body = Encoding.UTF8.GetString(document.Body.ToArray());
#else
var body = Encoding.UTF8.GetString(document.Body);
#endif

operation = new HotChocolate.Transport.OperationRequest(body, null, name, variables, extensions);
}

return new GraphQLHttpRequest(operation) { EnableFileUploads = hasFiles, };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,30 @@ public void Serialize_Request_With_Json()
Encoding.UTF8.GetString(stream.ToArray()).MatchSnapshot();
}

[Fact]
public void Serialize_Request_With_Id_And_Empty_Query()
{
// arrange
var json = JsonDocument.Parse(@"{ ""abc"": { ""def"": ""def"" } }");

// act
using var stream = new MemoryStream();
using var jsonWriter = new Utf8JsonWriter(stream, new() { Indented = true, });
var serializer = new JsonOperationRequestSerializer();
serializer.Serialize(
new OperationRequest(
"123",
"abc",
new EmptyDocument(),
new Dictionary<string, object?> { { "abc", json.RootElement }, },
strategy: RequestStrategy.PersistedQuery),
jsonWriter);
jsonWriter.Flush();

// assert
Encoding.UTF8.GetString(stream.ToArray()).MatchSnapshot();
}

[Fact]
public void Serialize_Request_With_Extensions()
{
Expand Down Expand Up @@ -123,4 +147,13 @@ private sealed class Document : IDocument

public DocumentHash Hash { get; } = new("MD5", "ABCDEF");
}

private sealed class EmptyDocument : IDocument
{
public OperationKind Kind => OperationKind.Query;

public ReadOnlySpan<byte> Body => Array.Empty<byte>();

public DocumentHash Hash { get; } = new("MD5", "ABCDEF");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"id": "123",
"operationName": "abc",
"variables": {
"abc": {
"abc": {
"def": "def"
}
}
}
}

0 comments on commit a2c1f1a

Please sign in to comment.