Comments (5)
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.
I guess it would be nice to have this mentioned somewhere in the docs.
from graphql.
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.
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.
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)
- Subscription graphql this on resolve does not access services being injected in the constructor HOT 1
- Support for @defer directive in GraphQL HOT 2
- @nestjs/graphql compatibility with ts-morph 22.0.0 HOT 1
- Regular Expression Denial of Service (ReDoS) vulnerability HOT 2
- Feat | clarifying `DefinitionsGeneratorOptions#defaultTypeMapping` supported types
- Incomplete schema produced with code-first approach: directives are omitted HOT 1
- @nestjs/graphql depends on vulnerable version of ws HOT 1
- Upgrade WS dependency - ws affected by a DoS when handling a request with many HTTP headers HOT 3
- v12.2.0 - Error: Schema must contain uniquely named types but contains multiple types named "DateTime"
- npm warn deprecated @apollo/[email protected] HOT 1
- Allow sortSchema via GraphQLDefinitionsFactory HOT 1
- NestJS GraphQL subscriptions not working with graphql-ws HOT 1
- Params with the Args decorator are not decorated in resolvers after inheritance HOT 1
- Support Deno HOT 1
- Improve deprecation Reason to ArgsOptions HOT 2
- @ResolveField identified as defined in resolver but not in schema HOT 1
- Inability to Use `transformSchema` and Custom Directives in Apollo Gateway Configuration with `@nestjs/graphql` HOT 1
- Allow ts-morph ^22.0.0 HOT 1
- Replace `fast-glob` with `fdir` or `tinyglobby` HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from graphql.