parse-graphql-json.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { buildClientSchema } from 'graphql';
  2. function stripBOM(content) {
  3. content = content.toString();
  4. // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  5. // because the buffer-to-string conversion in `fs.readFileSync()`
  6. // translates it to FEFF, the UTF-16 BOM.
  7. if (content.charCodeAt(0) === 0xfeff) {
  8. content = content.slice(1);
  9. }
  10. return content;
  11. }
  12. function parseBOM(content) {
  13. return JSON.parse(stripBOM(content));
  14. }
  15. export function parseGraphQLJSON(location, jsonContent, options) {
  16. let parsedJson = parseBOM(jsonContent);
  17. if (parsedJson.data) {
  18. parsedJson = parsedJson.data;
  19. }
  20. if (parsedJson.kind === 'Document') {
  21. return {
  22. location,
  23. document: parsedJson,
  24. };
  25. }
  26. else if (parsedJson.__schema) {
  27. const schema = buildClientSchema(parsedJson, options);
  28. return {
  29. location,
  30. schema,
  31. };
  32. }
  33. else if (typeof parsedJson === 'string') {
  34. return {
  35. location,
  36. rawSDL: parsedJson,
  37. };
  38. }
  39. throw new Error(`Not valid JSON content`);
  40. }