Skip to content

How to serve graphql schema directly instead of through a ‘schema.graphqls’ file

I’m trying to programmatically create a dynamic schema using the included webonyx/graphql extension like in this code snippet. Define my schema, it’s types, convert it to a string, paste its contents into the schema.graphqls and then flush the cache for Magento 2 to retrieve it. The schema is fine,

use GraphQLTypeDefinitionObjectType;
use GraphQLTypeDefinitionType;
use GraphQLTypeSchema;
use GraphQLUtilsSchemaPrinter;

        $queryType = new ObjectType([
            'name' => 'Query',
            'fields' => [
                $this->helper->getMainQueryName() => [
                    'type' => $this->generateType($scopeValues),
                ]
            ],
        ]);
        $schema = new Schema(['query' => $queryType]);
        $schemaString = SchemaPrinter::doPrint($schema);
        file_put_contents('ModulePath/etc/schema.graphqls', $schemaString);
        $this->helper->flushCache();

but the problem is that this code will not have write permissions, how do I serve the schema then, without writing to a schema in graphql?.