Created
April 27, 2020 19:17
-
-
Save acao/c558b6754c11f3a1a0767740cb37653d to your computer and use it in GitHub Desktop.
example schema loading utilities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
getIntrospectionQuery, | |
IntrospectionOptions, | |
IntrospectionQuery, | |
DocumentNode, | |
BuildSchemaOptions, | |
buildClientSchema, | |
buildASTSchema, | |
buildSchema | |
} from 'graphql'; | |
import type { GraphQLSchemaValidationOptions } from 'graphql/type/schema'; | |
export type SchemaConfig = { | |
uri: string; | |
introspectionOptions?: IntrospectionOptions; | |
validationOptions?: GraphQLSchemaValidationOptions; | |
requestOpts?: { | |
method: 'post' | 'get', | |
headers: { [name: string]: string } | |
} | |
}; | |
type IntrospectionSchemaResponse = { | |
responseType: 'introspection', | |
response: IntrospectionQuery | |
} | |
type ASTSchemaResponse = { | |
responseType: 'ast', | |
response: DocumentNode | |
} | |
type SDLSchemaResponse = { | |
responseType: 'sdl', | |
response: string | |
} | |
export type SchemaResponse = IntrospectionSchemaResponse | ASTSchemaResponse | SDLSchemaResponse | |
export type SchemaLoader = (config: SchemaConfig) => Promise<SchemaResponse | void> | |
export const defaultSchemaLoader: SchemaLoader = async ( | |
schemaConfig: SchemaConfig, | |
): Promise<SchemaResponse | void> => { | |
const rawResult = await fetch(schemaConfig.uri, { | |
method: schemaConfig?.requestOpts?.method ?? 'post', | |
body: JSON.stringify({ | |
query: getIntrospectionQuery(schemaConfig.introspectionOptions), | |
operationName: 'IntrospectionQuery', | |
}), | |
headers: { | |
'Content-Type': 'application/json', | |
credentials: 'omit', | |
...schemaConfig?.requestOpts?.headers | |
}, | |
}); | |
const introspectionResponse: { data: IntrospectionQuery } = await rawResult.json(); | |
if (!introspectionResponse || !introspectionResponse.data) { | |
throw Error(`error fetching introspection schema for ${schemaConfig.uri}`); | |
} | |
return { response: introspectionResponse.data, responseType: 'introspection' } | |
}; | |
export function buildSchemaFromResponse(schema: SchemaResponse, buildSchemaOptions?: BuildSchemaOptions) { | |
switch (schema.responseType) { | |
case "introspection": { | |
return buildClientSchema(schema.response, buildSchemaOptions) | |
} | |
case "ast": { | |
return buildASTSchema(schema.response, buildSchemaOptions); | |
} | |
case "sdl": { | |
return buildSchema(schema.response, buildSchemaOptions); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment