Skip to content

Instantly share code, notes, and snippets.

@zmitry
Created May 30, 2021 19:06
Show Gist options
  • Select an option

  • Save zmitry/97a38d8a701b2f9d74e4bfb1209c8580 to your computer and use it in GitHub Desktop.

Select an option

Save zmitry/97a38d8a701b2f9d74e4bfb1209c8580 to your computer and use it in GitHub Desktop.
import { makeRemoteExecutor } from '../lib/stiching/makeRemoteExecutor';
import { FastifyInstance } from 'fastify';
import fs from 'fs';
import { LoginInput, RegisterInput } from 'gen/resolvers.types';
import mercurius, { IResolvers } from 'mercurius';
import { AuthService } from 'services/auth/auth.service';
import { addMocksToSchema } from '@graphql-tools/mock';
import { stitchSchemas } from '@graphql-tools/stitch';
import { buildSchema } from 'graphql';
import { appConfig } from '../config';
type Context = { authorization: string; services: { auth: AuthService } };
declare module 'mercurius' {
interface MercuriusContext extends Context {}
}
export const resolvers: IResolvers<Context> = {
query_root: {
hello(_, _1, _2) {
return 'hello world';
},
},
mutation_root: {
login: (_, { input }: { input: LoginInput }, ctx) => ctx.services.auth.login(input, ctx.reply),
register: (_, { input }: { input: RegisterInput }, ctx) => ctx.services.auth.register(input, ctx.reply),
refreshToken: (_, _1, ctx) => ctx.services.auth.refreshToken(ctx.reply),
logout: (_, _1, ctx) => ctx.services.auth.logout(ctx.reply),
},
};
function makeSchema() {
const schema = fs.readFileSync(appConfig.appSchemaPath, { encoding: 'utf-8' }).toString();
const hasuraSchemaExecutor = makeRemoteExecutor(appConfig.hasuraEndpoint.http);
const hasuraSchema = fs.readFileSync(appConfig.hasuraSchemaPath, { encoding: 'utf-8' }).toString();
return stitchSchemas<Context>({
subschemas: [
{
schema: addMocksToSchema({ schema: buildSchema(hasuraSchema) }),
executor: hasuraSchemaExecutor,
// enabled if needed
// subscriber: makeRemoteSubscriber(appConfig.hasuraEndpoint.ws, {
// headers: {
// 'x-hasura-admin-secret': appConfig.hasuraSecret,
// },
// }),
},
],
typeDefs: schema,
});
}
export function addGraphqlGateway(app: FastifyInstance, services: Context['services']) {
app.register(mercurius, {
schema: makeSchema(),
resolvers: resolvers,
context: () => ({
services: services,
}),
path: '/api/graphql',
graphiql: 'playground',
defineMutation: true,
subscription: true,
logLevel: appConfig.logLevel,
});
return app;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment