apollo-server/src/core/runQuery.ts

94 lines
2.6 KiB
TypeScript
Raw Normal View History

import {
GraphQLSchema,
GraphQLResult,
Document,
parse,
validate,
execute,
formatError,
2016-07-02 22:51:17 -07:00
specifiedRules,
ValidationRule,
} from 'graphql';
export interface GqlResponse {
data?: Object;
errors?: Array<string>;
}
export interface QueryOptions {
schema: GraphQLSchema;
query: string | Document;
rootValue?: any;
context?: any;
variables?: { [key: string]: any };
operationName?: string;
logFunction?: Function;
2016-07-02 22:51:17 -07:00
validationRules?: Array<ValidationRule>;
// WARNING: these extra validation rules are only applied to queries
// submitted as string, not those submitted as Document!
formatError?: Function;
formatResponse?: Function;
}
function runQuery(options: QueryOptions): Promise<GraphQLResult> {
let documentAST: Document;
2016-07-02 22:51:17 -07:00
function format(errors: Array<Error>): Array<Error> {
// TODO: fix types! shouldn't have to cast.
// the blocker is that the typings aren't right atm:
// GraphQLResult returns Array<GraphQLError>, but the formatError function
// returns Array<GraphQLFormattedError>
return errors.map(options.formatError || formatError as any) as Array<Error>;
}
2016-06-24 17:16:33 -04:00
// if query is already an AST, don't parse or validate
if (typeof options.query === 'string') {
try {
// TODO: time this with log function
documentAST = parse(options.query as string);
} catch (syntaxError) {
2016-07-02 22:51:17 -07:00
return Promise.resolve({ errors: format([syntaxError]) });
}
// TODO: time this with log function
2016-07-02 22:51:17 -07:00
let rules = specifiedRules;
if (options.validationRules) {
rules = rules.concat(options.validationRules);
}
const validationErrors = validate(options.schema, documentAST, rules);
if (validationErrors.length) {
2016-07-02 22:51:17 -07:00
return Promise.resolve({ errors: format(validationErrors) });
}
} else {
documentAST = options.query as Document;
}
2016-06-24 16:57:52 -04:00
try {
return execute(
2016-06-24 17:16:33 -04:00
options.schema,
2016-06-24 16:57:52 -04:00
documentAST,
2016-06-24 17:16:33 -04:00
options.rootValue,
options.context,
options.variables,
options.operationName
).then(gqlResponse => {
let response = {
data: gqlResponse.data,
};
if (gqlResponse.errors) {
2016-07-02 22:51:17 -07:00
response['errors'] = format(gqlResponse.errors);
}
if (options.formatResponse) {
response = options.formatResponse(response);
}
return response;
});
2016-06-24 16:57:52 -04:00
} catch (executionError) {
2016-07-02 22:51:17 -07:00
return Promise.resolve({ errors: format([executionError]) });
2016-06-24 16:57:52 -04:00
}
}
export { runQuery };