UNPKG

2.42 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.printError = printError;
7
8var _location = require('../language/location');
9
10/**
11 * Prints a GraphQLError to a string, representing useful location information
12 * about the error's position in the source.
13 */
14function printError(error) {
15 var printedLocations = [];
16 if (error.nodes) {
17 error.nodes.forEach(function (node) {
18 if (node.loc) {
19 printedLocations.push(highlightSourceAtLocation(node.loc.source, (0, _location.getLocation)(node.loc.source, node.loc.start)));
20 }
21 });
22 } else if (error.source && error.locations) {
23 var source = error.source;
24 error.locations.forEach(function (location) {
25 printedLocations.push(highlightSourceAtLocation(source, location));
26 });
27 }
28 return printedLocations.length === 0 ? error.message : [error.message].concat(printedLocations).join('\n\n') + '\n';
29}
30
31/**
32 * Render a helpful description of the location of the error in the GraphQL
33 * Source document.
34 */
35/**
36 * Copyright (c) 2015-present, Facebook, Inc.
37 *
38 * This source code is licensed under the MIT license found in the
39 * LICENSE file in the root directory of this source tree.
40 *
41 *
42 */
43
44function highlightSourceAtLocation(source, location) {
45 var line = location.line;
46 var lineOffset = source.locationOffset.line - 1;
47 var columnOffset = getColumnOffset(source, location);
48 var contextLine = line + lineOffset;
49 var contextColumn = location.column + columnOffset;
50 var prevLineNum = (contextLine - 1).toString();
51 var lineNum = contextLine.toString();
52 var nextLineNum = (contextLine + 1).toString();
53 var padLen = nextLineNum.length;
54 var lines = source.body.split(/\r\n|[\n\r]/g);
55 lines[0] = whitespace(source.locationOffset.column - 1) + lines[0];
56 var outputLines = [source.name + ' (' + contextLine + ':' + contextColumn + ')', line >= 2 && lpad(padLen, prevLineNum) + ': ' + lines[line - 2], lpad(padLen, lineNum) + ': ' + lines[line - 1], whitespace(2 + padLen + contextColumn - 1) + '^', line < lines.length && lpad(padLen, nextLineNum) + ': ' + lines[line]];
57 return outputLines.filter(Boolean).join('\n');
58}
59
60function getColumnOffset(source, location) {
61 return location.line === 1 ? source.locationOffset.column - 1 : 0;
62}
63
64function whitespace(len) {
65 return Array(len + 1).join(' ');
66}
67
68function lpad(len, str) {
69 return whitespace(len - str.length) + str;
70}
\No newline at end of file