|
| 1 | +/* @flow */ |
| 2 | + |
| 3 | +import { graphql, TypeComposer, upperFirst } from 'graphql-compose'; |
| 4 | + |
| 5 | +const { isOutputType } = graphql; |
| 6 | + |
| 7 | +type GetValueOpts = { |
| 8 | + typeName: string, |
| 9 | + fieldName: string, |
| 10 | +}; |
| 11 | + |
| 12 | +export default class ObjectParser { |
| 13 | + static createTC(name: string, json: Object): TypeComposer { |
| 14 | + if (!json || typeof json !== 'object') { |
| 15 | + throw new Error('You provide empty object in second arg for `createTC` method.'); |
| 16 | + } |
| 17 | + const tc = TypeComposer.create(name); |
| 18 | + |
| 19 | + const fields = {}; |
| 20 | + Object.keys(json).forEach(k => { |
| 21 | + fields[k] = this.getValueType(json[k], { typeName: name, fieldName: k }); |
| 22 | + }); |
| 23 | + |
| 24 | + tc.setFields(fields); |
| 25 | + |
| 26 | + return tc; |
| 27 | + } |
| 28 | + |
| 29 | + static getValueType( |
| 30 | + value: any, |
| 31 | + opts: ?GetValueOpts |
| 32 | + ): string | [string] | graphql.GraphQLOutputType | TypeComposer { |
| 33 | + const typeOf = typeof value; |
| 34 | + |
| 35 | + if (typeOf === 'number') return 'Float'; |
| 36 | + if (typeOf === 'string') return 'String'; |
| 37 | + if (typeOf === 'boolean') return 'Boolean'; |
| 38 | + |
| 39 | + if (typeOf === 'object') { |
| 40 | + if (value === null) return 'JSON'; |
| 41 | + |
| 42 | + if (Array.isArray(value)) { |
| 43 | + const val = value[0]; |
| 44 | + if (Array.isArray(val)) return ['JSON']; |
| 45 | + return [(this.getValueType(val): any)]; |
| 46 | + } |
| 47 | + |
| 48 | + if (opts && opts.typeName && opts.fieldName) { |
| 49 | + return this.createTC(`${opts.typeName}_${upperFirst(opts.fieldName)}`, value); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + if (typeOf === 'function') { |
| 54 | + return this.getValueTypeFromFunction(value); |
| 55 | + } |
| 56 | + |
| 57 | + return 'JSON'; |
| 58 | + } |
| 59 | + |
| 60 | + static getValueTypeFromFunction( |
| 61 | + value: () => any |
| 62 | + ): string | graphql.GraphQLOutputType | TypeComposer { |
| 63 | + const type = value(); |
| 64 | + |
| 65 | + if (typeof type === 'string') return type; |
| 66 | + if (isOutputType(type)) return type; |
| 67 | + if (type instanceof TypeComposer) return type; |
| 68 | + |
| 69 | + throw new Error( |
| 70 | + 'Your type function should return: `string`, `GraphQLOutputType`, `TypeComposer`.' |
| 71 | + ); |
| 72 | + } |
| 73 | +} |
0 commit comments