Home > database >  How to generate GraphQL Schema from schema.graphql file in PHP
How to generate GraphQL Schema from schema.graphql file in PHP

Time:09-09

I have created the schema.graphql file in PHP using the following code:

$data = SchemaPrinter::doPrint($schema);
file_put_contents('/var/cache/Graphql/schema.graphql', $data);

Now I want to create new schema using this file content. How to achieve this?

CodePudding user response:

I have created the schema from schema.graphql using the BuildSchema::build().

By default, such schema is created without any resolvers. So we need to define our custom resolvers as follows:

$contents = file_get_contents($this->projectDir.'/config/schema.graphql');
$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {
    $name = $typeConfig['name'];
    if ($name === 'Query') {
       $typeConfig['resolveField'] =
           function ($source, $args, $context, ResolveInfo $info) {
               if ($info->fieldDefinition->name == 'login') {
                   if ($args['userName'] === 'test' && $args['password'] === '1234') {
                       return "Valid User.";
                   } else {
                       return "Invalid User";
                   }
               } elseif ($info->fieldDefinition->name == 'validateUser') {
                   if ($args['age'] < 18) {
                       return ['userId' => $args['userId'], 'category' => 'Not eligible for voting'];
                    } 
                    }
                }
                }
            ;
        }
        return $typeConfig;
    };
$schema = BuildSchema::build($contents, $typeConfigDecorator);
  • Related