json.mjs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { Kind, GraphQLScalarType } from 'graphql'
  2. function ensureObject (value) {
  3. if (typeof value !== 'object' || value === null || Array.isArray(value)) {
  4. throw new TypeError(`JSONObject cannot represent non-object value: ${value}`)
  5. }
  6. return value
  7. }
  8. function parseLiteral (typeName, ast, variables) {
  9. switch (ast.kind) {
  10. case Kind.STRING:
  11. case Kind.BOOLEAN:
  12. return ast.value
  13. case Kind.INT:
  14. case Kind.FLOAT:
  15. return parseFloat(ast.value)
  16. case Kind.OBJECT:
  17. return parseObject(typeName, ast, variables)
  18. case Kind.LIST:
  19. return ast.values.map((n) => parseLiteral(typeName, n, variables))
  20. case Kind.NULL:
  21. return null
  22. case Kind.VARIABLE:
  23. return variables ? variables[ast.name.value] : undefined
  24. default:
  25. throw new TypeError(`${typeName} cannot represent value: ${ast}`)
  26. }
  27. }
  28. function parseObject (typeName, ast, variables) {
  29. const value = Object.create(null)
  30. ast.fields.forEach((field) => {
  31. // eslint-disable-next-line no-use-before-define
  32. value[field.name.value] = parseLiteral(typeName, field.value, variables)
  33. })
  34. return value
  35. }
  36. export default new GraphQLScalarType({
  37. name: 'JSON',
  38. description:
  39. 'The `JSON` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).',
  40. specifiedByUrl:
  41. 'http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf',
  42. serialize: ensureObject,
  43. parseValue: ensureObject,
  44. parseLiteral: (ast, variables) => {
  45. if (ast.kind !== Kind.OBJECT) {
  46. throw new TypeError(`JSONObject cannot represent non-object value: ${ast}`)
  47. }
  48. return parseObject('JSONObject', ast, variables)
  49. }
  50. })