json.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const { Kind, GraphQLScalarType } = require('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. module.exports = {
  37. JSON: new GraphQLScalarType({
  38. name: 'JSON',
  39. description:
  40. 'The `JSON` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).',
  41. specifiedByUrl:
  42. 'http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf',
  43. serialize: ensureObject,
  44. parseValue: ensureObject,
  45. parseLiteral: (ast, variables) => {
  46. if (ast.kind !== Kind.OBJECT) {
  47. throw new TypeError(`JSONObject cannot represent non-object value: ${ast}`)
  48. }
  49. return parseObject('JSONObject', ast, variables)
  50. }
  51. })
  52. }