Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added native support for using apollo-link as the network layer #409

Merged
merged 2 commits into from
Oct 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Change log

### vNEXT
* Added support for passing an Apollo Link instead of a fetcher

### v2.0.0

* Add schema merging utilities [PR #382](https://github.com/apollographql/graphql-tools/pull/382)

### v1.2.3
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
},
"homepage": "https://github.com/apollostack/graphql-tools#readme",
"dependencies": {
"apollo-link": "^0.7.0",
"deprecated-decorator": "^0.1.6",
"uuid": "^3.1.0"
},
Expand Down
22 changes: 15 additions & 7 deletions src/stitching/introspectSchema.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import { GraphQLSchema } from 'graphql';
import { GraphQLSchema, parse } from 'graphql';
import { introspectionQuery, buildClientSchema } from 'graphql';
import { Fetcher } from './makeRemoteExecutableSchema';
import { ApolloLink, execute, makePromise } from 'apollo-link';
import { Fetcher, fetcherToLink } from './makeRemoteExecutableSchema';

const parsedIntrospectionQuery = parse(introspectionQuery);

export default async function introspectSchema(
fetcher: Fetcher,
link: ApolloLink | Fetcher,
context?: { [key: string]: any },
): Promise<GraphQLSchema> {
const introspectionResult = await fetcher({
query: introspectionQuery,
context,
});
if (!(link as ApolloLink).request) {
link = fetcherToLink(link as Fetcher);
}
const introspectionResult = await makePromise(
execute(link as ApolloLink, {
query: parsedIntrospectionQuery,
context,
}),
);
if (introspectionResult.errors || !introspectionResult.data.__schema) {
throw introspectionResult.errors;
} else {
Expand Down
62 changes: 47 additions & 15 deletions src/stitching/makeRemoteExecutableSchema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { printSchema, print, ExecutionResult, Kind, ValueNode } from 'graphql';
import { printSchema, print, Kind, ValueNode, ExecutionResult } from 'graphql';
import { execute, makePromise, ApolloLink, Observable } from 'apollo-link';

import {
GraphQLFieldResolver,
GraphQLSchema,
Expand All @@ -25,25 +27,51 @@ export type Fetcher = (
},
) => Promise<ExecutionResult>;

export const fetcherToLink = (fetcher: Fetcher): ApolloLink => {
return new ApolloLink(operation => {
return new Observable(observer => {
const { query, operationName, variables } = operation;
const context = operation.getContext();
fetcher({
query: typeof query === 'string' ? query : print(query),
operationName,
variables,
context,
})
.then((result: ExecutionResult) => {
observer.next(result);
observer.complete();
})
.catch(observer.error.bind(observer));
});
});
};

export default function makeRemoteExecutableSchema({
schema,
link,
fetcher,
}: {
schema: GraphQLSchema;
fetcher: Fetcher;
link?: ApolloLink;
fetcher?: Fetcher;
}): GraphQLSchema {
if (fetcher && !link) {
link = fetcherToLink(fetcher);
}

const queryType = schema.getQueryType();
const queries = queryType.getFields();
const queryResolvers: IResolverObject = {};
Object.keys(queries).forEach(key => {
queryResolvers[key] = createResolver(fetcher);
queryResolvers[key] = createResolver(link);
});
let mutationResolvers: IResolverObject = {};
const mutationType = schema.getMutationType();
if (mutationType) {
const mutations = mutationType.getFields();
Object.keys(mutations).forEach(key => {
mutationResolvers[key] = createResolver(fetcher);
mutationResolvers[key] = createResolver(link);
});
}

Expand Down Expand Up @@ -88,18 +116,22 @@ export default function makeRemoteExecutableSchema({
});
}

function createResolver(fetcher: Fetcher): GraphQLFieldResolver<any, any> {
function createResolver(link: ApolloLink): GraphQLFieldResolver<any, any> {
return async (root, args, context, info) => {
const operation = print(info.operation);
const fragments = Object.keys(info.fragments)
.map(fragment => print(info.fragments[fragment]))
.join('\n');
const query = `${operation}\n${fragments}`;
const result = await fetcher({
query,
variables: info.variableValues,
context,
});
const fragments = Object.keys(info.fragments).map(
fragment => info.fragments[fragment],
);
const document = {
kind: Kind.DOCUMENT,
definitions: [info.operation, ...fragments],
};
const result = await makePromise(
execute(link, {
query: document,
variables: info.variableValues,
context,
}),
);
const fieldName = info.fieldNodes[0].alias
? info.fieldNodes[0].alias.value
: info.fieldName;
Expand Down
27 changes: 24 additions & 3 deletions src/test/testingSchemas.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import {
GraphQLSchema,
graphql,
print,
Kind,
GraphQLScalarType,
ValueNode,
} from 'graphql';
import { ApolloLink, Observable } from 'apollo-link';
import { makeExecutableSchema } from '../schemaGenerator';
import { IResolvers } from '../Interfaces';
import makeRemoteExecutableSchema from '../stitching/makeRemoteExecutableSchema';
Expand Down Expand Up @@ -485,7 +487,26 @@ export const bookingSchema: GraphQLSchema = makeExecutableSchema({
});

// Pretend this schema is remote
async function makeSchemaRemote(schema: GraphQLSchema) {
async function makeSchemaRemoteFromLink(schema: GraphQLSchema) {
const link = new ApolloLink((operation) => {
return new Observable(observer => {
const { query, operationName, variables } = operation;
const context = operation.getContext();
graphql(schema, print(query), null, context, variables, operationName)
.then((result) => {
observer.next(result);
observer.complete();
})
.catch(observer.error.bind(observer));
});
});

const clientSchema = await introspectSchema(link);
return makeRemoteExecutableSchema({ schema: clientSchema, link });
}

// ensure fetcher support exists from the 2.0 api
async function makeExecutableSchemaFromFetcher(schema: GraphQLSchema) {
const fetcher: Fetcher = ({ query, operationName, variables, context }) => {
return graphql(schema, query, null, context, variables, operationName);
};
Expand All @@ -494,5 +515,5 @@ async function makeSchemaRemote(schema: GraphQLSchema) {
return makeRemoteExecutableSchema({ schema: clientSchema, fetcher });
}

export const remotePropertySchema = makeSchemaRemote(propertySchema);
export const remoteBookingSchema = makeSchemaRemote(bookingSchema);
export const remotePropertySchema = makeSchemaRemoteFromLink(propertySchema);
export const remoteBookingSchema = makeExecutableSchemaFromFetcher(bookingSchema);