2018-06-21 22:54:53 +02:00
|
|
|
import * as lambda from 'aws-lambda';
|
|
|
|
import {
|
|
|
|
GraphQLOptions,
|
|
|
|
HttpQueryError,
|
|
|
|
runHttpQuery,
|
|
|
|
} from 'apollo-server-core';
|
|
|
|
|
|
|
|
export interface LambdaGraphQLOptionsFunction {
|
|
|
|
(event: lambda.APIGatewayProxyEvent, context: lambda.Context):
|
|
|
|
| GraphQLOptions
|
|
|
|
| Promise<GraphQLOptions>;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function graphqlLambda(
|
|
|
|
options: GraphQLOptions | LambdaGraphQLOptionsFunction,
|
|
|
|
): lambda.APIGatewayProxyHandler {
|
|
|
|
if (!options) {
|
|
|
|
throw new Error('Apollo Server requires options.');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (arguments.length > 1) {
|
|
|
|
throw new Error(
|
|
|
|
`Apollo Server expects exactly one argument, got ${arguments.length}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const graphqlHandler: lambda.APIGatewayProxyHandler = (
|
|
|
|
event,
|
|
|
|
context,
|
|
|
|
callback,
|
|
|
|
): void => {
|
|
|
|
if (event.httpMethod === 'POST' && !event.body) {
|
|
|
|
return callback(null, {
|
|
|
|
body: 'POST body missing.',
|
|
|
|
statusCode: 500,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
runHttpQuery([event, context], {
|
|
|
|
method: event.httpMethod,
|
|
|
|
options: options,
|
|
|
|
query:
|
|
|
|
event.httpMethod === 'POST'
|
|
|
|
? JSON.parse(event.body)
|
|
|
|
: (event.queryStringParameters as any),
|
|
|
|
request: {
|
|
|
|
url: event.path,
|
|
|
|
method: event.httpMethod,
|
|
|
|
headers: event.headers as any,
|
|
|
|
},
|
|
|
|
}).then(
|
2018-06-21 15:07:01 -07:00
|
|
|
({ graphqlResponse, responseInit }) => {
|
2018-06-21 22:54:53 +02:00
|
|
|
callback(null, {
|
2018-06-21 15:07:01 -07:00
|
|
|
body: graphqlResponse,
|
2018-06-21 22:54:53 +02:00
|
|
|
statusCode: 200,
|
2018-06-21 15:07:01 -07:00
|
|
|
headers: responseInit.headers,
|
2018-06-21 22:54:53 +02:00
|
|
|
});
|
|
|
|
},
|
|
|
|
(error: HttpQueryError) => {
|
|
|
|
if ('HttpQueryError' !== error.name) return callback(error);
|
|
|
|
callback(null, {
|
|
|
|
body: error.message,
|
|
|
|
statusCode: error.statusCode,
|
|
|
|
headers: error.headers,
|
|
|
|
});
|
|
|
|
},
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
return graphqlHandler;
|
|
|
|
}
|