Skip to content

Commit 22a37fe

Browse files
committed
feat(TypeMapper): add parseTypesFromString parseTypesFromAst methods
Related graphql-compose#107
1 parent c47c5c5 commit 22a37fe

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/__tests__/typeMapper-test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -663,4 +663,30 @@ describe('TypeMapper', () => {
663663
expect(acm.a2.type).toBe(GraphQLInt);
664664
});
665665
});
666+
667+
describe('parseTypesFrom... methods', () => {
668+
it('parseTypesFromString()', () => {
669+
const gql = `
670+
type User {
671+
name: String
672+
}
673+
674+
type Article {
675+
title: String
676+
}
677+
678+
input Record {
679+
id: ID
680+
ts: Int
681+
}
682+
`;
683+
684+
const ts = typeMapper.parseTypesFromString(gql);
685+
expect(Array.from(ts.keys())).toEqual(['User', 'Article', 'Record']);
686+
687+
expect(ts.get('User')).toBeInstanceOf(GraphQLObjectType);
688+
expect(ts.get('Article')).toBeInstanceOf(GraphQLObjectType);
689+
expect(ts.get('Record')).toBeInstanceOf(GraphQLInputObjectType);
690+
});
691+
});
666692
});

src/typeMapper.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ import type { Thunk } from './utils/definitions';
8787
import TypeComposer from './typeComposer';
8888
import InputTypeComposer from './inputTypeComposer';
8989
import Resolver from './resolver';
90+
import TypeStorage from './typeStorage';
9091
import GQC from './gqc';
9192

9293
export type TypeDefinitionString = string; // eg type Name { field: Int }
@@ -188,6 +189,27 @@ class TypeMapper {
188189
return undefined;
189190
}
190191

192+
parseTypesFromString(str: string): TypeStorage<GraphQLNamedType> {
193+
const astDocument: DocumentNode = parse(str);
194+
195+
if (!astDocument || astDocument.kind !== 'Document') {
196+
throw new Error('You should provide correct SDL syntax.');
197+
}
198+
199+
return this.parseTypesFromAst(astDocument);
200+
}
201+
202+
parseTypesFromAst(astDocument: DocumentNode): TypeStorage<GraphQLNamedType> {
203+
const typeStorage = new TypeStorage();
204+
205+
for (let i = 0; i < astDocument.definitions.length; i++) {
206+
const def = astDocument.definitions[i];
207+
const type = makeSchemaDef(def);
208+
typeStorage.set(type.name, type);
209+
}
210+
return typeStorage;
211+
}
212+
191213
convertOutputFieldConfig<TSource, TContext>(
192214
composeFC: ComposeFieldConfig<TSource, TContext>,
193215
fieldName?: string = '',

0 commit comments

Comments
 (0)