Coder Social home page Coder Social logo

Comments (5)

vnenkpet avatar vnenkpet commented on September 1, 2024

Nevermind. I think I figured it out, we can just write an Apollo Server Plugin which does the trick:

import {
  ApolloServerPlugin,
  GraphQLRequestContext,
  GraphQLRequestContextWillSendResponse,
  GraphQLRequestListener,
} from '@apollo/server';
import { addMocksToSchema } from '@graphql-tools/mock';
import { Logger } from '@nestjs/common';
import { graphql } from 'graphql';

export class MocksApolloPlugin implements ApolloServerPlugin {
  private readonly logger = new Logger(MocksApolloPlugin.name);

  private readonly resolvers: Record<string, any> | undefined;
  private readonly mocks: Record<string, any> | undefined;

  constructor({
    resolvers,
    mocks,
  }: {
    resolvers?: Record<string, any>;
    mocks?: Record<string, any>;
  }) {
    this.resolvers = resolvers;
    this.mocks = mocks;
  }

  async requestDidStart(
    requestContext: GraphQLRequestContext<any>,
  ): Promise<GraphQLRequestListener<any>> {
    const resolvers = this.resolvers;
    const mocks = this.mocks;

    return {
      async willSendResponse(
        requestContext: GraphQLRequestContextWillSendResponse<any>,
      ) {
        const mockedSchema = addMocksToSchema({
          schema: requestContext.schema,
          resolvers,
          mocks,
          preserveResolvers: false,
        });
        if (requestContext.response.body.kind === 'single') {
          const result = await graphql({
            schema: mockedSchema,
            source: requestContext.source,
            variableValues: requestContext.request.variables,
          });
          requestContext.response.body.singleResult.data = (result.data ||
            {}) as Record<string, unknown>;
        }
      },
    };
  }
}

and then just add it to the "plugins" field of the GraphQLModule, eg:

          plugins: [
            ApolloServerPluginLandingPageLocalDefault({
              includeCookies: true,
              embed: true,
            }),
            new MocksApolloPlugin({
              resolvers: mockResolvers,
            }),
          ],

from graphql.

vnenkpet avatar vnenkpet commented on September 1, 2024

I guess it would be nice to have this mentioned somewhere in the docs.

from graphql.

vnenkpet avatar vnenkpet commented on September 1, 2024

Actually, just noticed my solution isn't exactly right, because while it does return mocked response, but it still executes the actual resolver. I suppose it should be doable though.

from graphql.

vnenkpet avatar vnenkpet commented on September 1, 2024

This seems to be so far doing what I want:

import {
  ApolloServerPlugin,
  GraphQLRequestContext,
  GraphQLRequestContextResponseForOperation,
  GraphQLRequestListener,
  GraphQLResponse,
  HeaderMap,
} from '@apollo/server';
import { addMocksToSchema } from '@graphql-tools/mock';
import { Logger } from '@nestjs/common';
import { graphql } from 'graphql';

export class MocksApolloPlugin implements ApolloServerPlugin {
  private readonly logger = new Logger(MocksApolloPlugin.name);

  private readonly resolvers: Record<string, any> | undefined;
  private readonly mocks: Record<string, any> | undefined;
  private readonly isEnabled: boolean;

  constructor({
    resolvers,
    mocks,
    isEnabled,
  }: {
    resolvers?: Record<string, any>;
    mocks?: Record<string, any>;
    isEnabled: boolean;
  }) {
    this.resolvers = resolvers;
    this.mocks = mocks;
    this.isEnabled = isEnabled;
  }

  async requestDidStart(
    requestContext: GraphQLRequestContext<any>,
  ): Promise<GraphQLRequestListener<any>> {
    const resolvers = this.resolvers;
    const mocks = this.mocks;
    const isEnabled = this.isEnabled;

    return {
      async responseForOperation(
        requestContext: GraphQLRequestContextResponseForOperation<any>,
      ): Promise<GraphQLResponse | null> {
        if (!isEnabled) {
          return null;
        }

        const mockedSchema = addMocksToSchema({
          schema: requestContext.schema,
          resolvers,
          mocks,
          preserveResolvers: false,
        });

        const result = await graphql({
          schema: mockedSchema,
          source: requestContext.source,
          variableValues: requestContext.request.variables,
        });

        return {
          body: { kind: 'single', singleResult: { data: result.data || {} } },
          http: { headers: new HeaderMap() },
        };
      },
    };
  }
}

from graphql.

vnenkpet avatar vnenkpet commented on September 1, 2024

Alternatively I also found out it's possible to simply do this:

    schema: addMocksToSchema({
      schema: makeExecutableSchema({
        typeDefs: await readFile('src/schema.gql', 'utf-8'),
      }),
      mocks: graphqlMocks,
    }),

Closing then.

from graphql.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.