2017-12-04 12:44:17 +03:00
|
|
|
import AdonisContext from '@adonisjs/framework/src/Context';
|
2018-01-09 00:08:01 +01:00
|
|
|
import {
|
|
|
|
GraphQLOptions,
|
|
|
|
HttpQueryError,
|
|
|
|
runHttpQuery,
|
|
|
|
} from 'apollo-server-core';
|
2017-12-04 12:44:17 +03:00
|
|
|
import * as GraphiQL from 'apollo-server-module-graphiql';
|
|
|
|
|
|
|
|
export interface AdonisGraphQLOptionsFunction {
|
|
|
|
(ctx: AdonisContext): GraphQLOptions | Promise<GraphQLOptions>;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface AdonisHandler {
|
|
|
|
(req: any, next): void;
|
|
|
|
}
|
|
|
|
|
2018-01-09 00:08:01 +01:00
|
|
|
export function graphqlAdonis(
|
|
|
|
options: GraphQLOptions | AdonisGraphQLOptionsFunction,
|
|
|
|
): AdonisHandler {
|
2017-12-04 12:44:17 +03:00
|
|
|
if (!options) {
|
|
|
|
throw new Error('Apollo Server requires options.');
|
|
|
|
}
|
|
|
|
if (arguments.length > 1) {
|
2018-01-09 00:08:01 +01:00
|
|
|
throw new Error(
|
|
|
|
`Apollo Server expects exactly one argument, got ${arguments.length}`,
|
|
|
|
);
|
2017-12-04 12:44:17 +03:00
|
|
|
}
|
|
|
|
return (ctx: AdonisContext): Promise<void> => {
|
|
|
|
const { request, response } = ctx;
|
|
|
|
const method = request.method();
|
|
|
|
const query = method === 'POST' ? request.post() : request.get();
|
|
|
|
return runHttpQuery([ctx], {
|
2018-01-09 00:08:01 +01:00
|
|
|
method,
|
|
|
|
options,
|
|
|
|
query,
|
|
|
|
}).then(
|
|
|
|
gqlResponse => {
|
|
|
|
response.json(gqlResponse);
|
|
|
|
},
|
|
|
|
(error: HttpQueryError) => {
|
|
|
|
if ('HttpQueryError' !== error.name) {
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
if (error.headers) {
|
|
|
|
Object.keys(error.headers).forEach(header => {
|
|
|
|
response.header(header, error.headers[header]);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
response.status(error.statusCode).send(error.message);
|
|
|
|
},
|
|
|
|
);
|
2017-12-04 12:44:17 +03:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface AdonisGraphiQLOptionsFunction {
|
|
|
|
(ctx: AdonisContext): GraphiQL.GraphiQLData | Promise<GraphiQL.GraphiQLData>;
|
|
|
|
}
|
|
|
|
|
2018-01-09 00:08:01 +01:00
|
|
|
export function graphiqlAdonis(
|
|
|
|
options: GraphiQL.GraphiQLData | AdonisGraphiQLOptionsFunction,
|
|
|
|
) {
|
2017-12-04 12:44:17 +03:00
|
|
|
return (ctx: AdonisContext): Promise<void> => {
|
|
|
|
const { request, response } = ctx;
|
|
|
|
const query = request.get();
|
2018-01-09 00:08:01 +01:00
|
|
|
return GraphiQL.resolveGraphiQLString(query, options, ctx).then(
|
|
|
|
graphiqlString => {
|
2017-12-04 12:44:17 +03:00
|
|
|
response.type('text/html').send(graphiqlString);
|
2018-01-09 00:08:01 +01:00
|
|
|
},
|
|
|
|
(error: HttpQueryError) => {
|
2017-12-04 12:44:17 +03:00
|
|
|
response.status(500).send(error.message);
|
2018-01-09 00:08:01 +01:00
|
|
|
},
|
|
|
|
);
|
2017-12-04 12:44:17 +03:00
|
|
|
};
|
|
|
|
}
|