Skip to content

Instantly share code, notes, and snippets.

@0xR
Created August 22, 2015 11:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xR/b597ef5c5718cbc093cf to your computer and use it in GitHub Desktop.
Save 0xR/b597ef5c5718cbc093cf to your computer and use it in GitHub Desktop.
// Usage: import makeTypeDef from './graphql-schema-creator.js';
// makeTypeDef('mynewtype', myTypeValue);
import {
GraphQLObjectType,
GraphQLNonNull,
GraphQLSchema,
GraphQLString,
GraphQLList,
GraphQLInt,
GraphQLFloat,
GraphQLBoolean
} from 'graphql/type';
const isObject = jsObject =>
(typeof jsObject === "object" && !Array.isArray(jsObject) && jsObject !== null);
const makeArrayTypedef = (name, jsArray) => {
if (jsArray[0]) {
return new GraphQLList(makeTypeDef(name, jsArray[0]));
} else {
return GraphQLString;
}
};
const makeFieldDescription = (name, type) => ({type, description: `[GENERATED] field ${name}`});
const objectPropsToFields = jsObject =>
Object.keys(jsObject)
.reduce((acc, key) => {
const type = makeFieldDescription(key, makeTypeDef(key, jsObject[key]));
return type ? {
...acc,
[key]: type
} : acc
}, {});
const makeObjectTypeDef = (name, jsObject) =>
new GraphQLObjectType({
name: name,
description: `[GENERATED] object ${name}`,
fields: objectPropsToFields(jsObject)
});
const makeTypeDef = (name, jsValue) => {
switch (true) {
case isObject(jsValue):
return makeObjectTypeDef(name, jsValue);
case Array.isArray(jsValue):
return makeArrayTypedef(name, jsValue);
case typeof jsValue === 'number':
if (jsValue % 1 === 0) {
return GraphQLInt;
} else {
return GraphQLFloat;
}
case typeof jsValue === 'string':
return GraphQLString;
case typeof jsValue === 'boolean':
return GraphQLBoolean;
default:
console.warn('JS type ignored:', jsValue);
return undefined;
}
};
export default makeTypeDef;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment