I noticed that in my own code (I use Lighthouse PHP for implementation GraphQL API) quite often I first describe the input type in the schema, then I describe the object for this type (DTO). It creates a sense of repetition and makes type system maintenance more difficult, so I decided to add the ability to programmatically generate types for the schema by its type declaration in code. So in my project I expanded this recommendation for third case: DTO for custom resolvers.
You can install the package via composer:
composer require epalshin/object-to-graphql
use GraphQL\Type\Definition\ObjectType;
use Palshin\ObjectToGraphQL\ObjectToGraphQL;
use Palshin\ObjectToGraphQL\Attributes\GraphQLArrayType;
use Palshin\ObjectToGraphQL\Attributes\GraphQLObjectType;
#[GraphQLObjectType(typeCategory: ObjectToGraphQL::TYPE_CATEGORY_INPUT)]
class ProductCreateDTO
{
public string $name;
public string $description;
public float $price;
public bool $isPublic;
#[GraphQLArrayType(ObjectToGraphQL::STRING, allowsNull: false)]
public array $photoUrls;
public ?ProductCategoryCreateDTO $category;
}
class ProductCategoryCreateDTO
{
public string $name;
public string $description;
public int $sortOrder;
}
$objectToGraphQL = new ObjectToGraphQL();
[ $productCreateDto, $productCategoryCreateDto ] = $objectToGraphQL->getObjectTypes(ProductCreateDTO::class);
// and now you can register $objectType in your schema
$mutationType = new ObjectType([
'name' => 'Mutation',
'fields' => [
'productCreate' => [
'type' => $product,
'args' => [
'input' => $productCreateDto,
],
'resolve' => function($rootValue, $args) {
// TODO
}
]
]
]);
The resulting GraphQL schema will be:
input ProductCreateDTOInput {
name: String!
description: String!
price: Float!
isPublic: Boolean!
photoUrls: [String!]!
category: ProductCategoryCreateDTOInput
}
input ProductCategoryCreateDTOInput {
name: String!
description: String!
sortOrder: Int!
}
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
- Add cyclic addition of types to schema
- Add processing for union types
- Add processing for type category and suffixes parameters passing through attribute
- Add strict mode for early error detection
- Add custom exceptions
- Write more tests
- Add possibility for adding description for generated types
The MIT License (MIT). Please see License File for more information.