Skip to content

Commit

Permalink
enhance(utils): refactor and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan committed May 27, 2021
1 parent 9fe4598 commit 982c8f5
Show file tree
Hide file tree
Showing 24 changed files with 242 additions and 547 deletions.
5 changes: 5 additions & 0 deletions .changeset/smart-donuts-care.md
@@ -0,0 +1,5 @@
---
'@graphql-tools/utils': minor
---

enhance(utils): refactor and cleanup
4 changes: 2 additions & 2 deletions packages/import/tests/schema/import-schema.spec.ts
Expand Up @@ -923,12 +923,12 @@ describe('importSchema', () => {
type Level1 {
id: ID!
}
type Level2 {
id: ID!
level1: Level1
}
type Level3 {
id: ID!
level2: Level2
Expand Down
4 changes: 3 additions & 1 deletion packages/loaders/apollo-engine/package.json
Expand Up @@ -20,9 +20,11 @@
"graphql": "^14.0.0 || ^15.0.0"
},
"dependencies": {
"@ardatan/aggregate-error": "0.0.6",
"@graphql-tools/utils": "^7.0.0",
"cross-fetch": "3.1.4",
"tslib": "~2.2.0"
"tslib": "~2.2.0",
"sync-fetch": "0.3.0"
},
"publishConfig": {
"access": "public",
Expand Down
178 changes: 48 additions & 130 deletions packages/loaders/apollo-engine/src/index.ts
@@ -1,6 +1,7 @@
import { SchemaLoader, Source, SingleFileOptions } from '@graphql-tools/utils';
import { SchemaLoader, Source, SingleFileOptions, parseGraphQLSDL } from '@graphql-tools/utils';
import { fetch } from 'cross-fetch';
import { buildClientSchema } from 'graphql';
import AggregateError from '@ardatan/aggregate-error';
import syncFetch from 'sync-fetch';

/**
* Additional options for loading from Apollo Engine
Expand All @@ -25,49 +26,63 @@ export class ApolloEngineLoader implements SchemaLoader<ApolloEngineOptions> {
return 'apollo-engine';
}

private getFetchArgs(options: ApolloEngineOptions): [string, RequestInit] {
return [
options.engine.endpoint || DEFAULT_APOLLO_ENDPOINT,
{
method: 'POST',
headers: {
'x-api-key': options.engine.apiKey,
'apollo-client-name': 'Apollo Language Server',
'apollo-client-reference-id': '146d29c0-912c-46d3-b686-920e52586be6',
'apollo-client-version': '2.6.8',
'Content-Type': 'application/json',
Accept: 'application/json',
...options.headers,
},
body: JSON.stringify({
query: SCHEMA_QUERY,
variables: {
id: options.graph,
tag: options.variant,
},
}),
},
];
}

async canLoad(ptr: string) {
return typeof ptr === 'string' && ptr === 'apollo-engine';
return this.canLoadSync(ptr);
}

canLoadSync() {
return false;
canLoadSync(ptr: string) {
return typeof ptr === 'string' && ptr === 'apollo-engine';
}

async load(_: 'apollo-engine', options: ApolloEngineOptions): Promise<Source> {
const response = await fetch(options.engine.endpoint || DEFAULT_APOLLO_ENDPOINT, {
method: 'POST',
headers: {
'x-api-key': options.engine.apiKey,
'apollo-client-name': 'Apollo Language Server',
'apollo-client-reference-id': '146d29c0-912c-46d3-b686-920e52586be6',
'apollo-client-version': '2.6.8',
'Content-Type': 'application/json',
Accept: 'application/json',
...options.headers,
},
body: JSON.stringify({
query: SCHEMA_QUERY,
variables: {
id: options.graph,
tag: options.variant,
},
}),
});
async load(pointer: 'apollo-engine', options: ApolloEngineOptions): Promise<Source> {
const fetchArgs = this.getFetchArgs(options);
const response = await fetch(...fetchArgs);

const { data, errors } = await response.json();

if (errors) {
throw new Error(errors.map(({ message }: Error) => message).join('\n'));
throw new AggregateError(errors);
}

return {
location: 'apollo-engine',
schema: buildClientSchema(data.service.schema),
};
return parseGraphQLSDL(pointer, data.service.schema.document, options);
}

loadSync(): never {
throw new Error('Loader ApolloEngine has no sync mode');
loadSync(pointer: 'apollo-engine', options: ApolloEngineOptions): Source {
const fetchArgs = this.getFetchArgs(options);
const response = syncFetch(...fetchArgs);

const { data, errors } = response.json();

if (errors) {
throw new AggregateError(errors);
}

return parseGraphQLSDL(pointer, data.service.schema.document, options);
}
}

Expand All @@ -80,104 +95,7 @@ export const SCHEMA_QUERY = /* GraphQL */ `
... on Service {
__typename
schema(tag: $tag) {
hash
__schema: introspection {
queryType {
name
}
mutationType {
name
}
subscriptionType {
name
}
types(filter: { includeBuiltInTypes: true }) {
...IntrospectionFullType
}
directives {
name
description
locations
args {
...IntrospectionInputValue
}
}
}
}
}
}
}
fragment IntrospectionFullType on IntrospectionType {
kind
name
description
fields {
name
description
args {
...IntrospectionInputValue
}
type {
...IntrospectionTypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...IntrospectionInputValue
}
interfaces {
...IntrospectionTypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...IntrospectionTypeRef
}
}
fragment IntrospectionInputValue on IntrospectionInputValue {
name
description
type {
...IntrospectionTypeRef
}
defaultValue
}
fragment IntrospectionTypeRef on IntrospectionType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
document
}
}
}
Expand Down
33 changes: 11 additions & 22 deletions packages/loaders/code-file/src/index.ts
@@ -1,4 +1,4 @@
import { Kind, isSchema, print } from 'graphql';
import { isSchema, GraphQLSchema, DocumentNode } from 'graphql';
import {
SchemaPointerSingle,
DocumentPointerSingle,
Expand All @@ -9,7 +9,7 @@ import {
asArray,
isValidPath,
parseGraphQLSDL,
printSchemaWithDirectives,
isDocumentNode,
} from '@graphql-tools/utils';
import {
GraphQLTagPluckOptions,
Expand All @@ -19,7 +19,7 @@ import {
import { tryToLoadFromExport, tryToLoadFromExportSync } from './load-from-module';
import { isAbsolute, resolve } from 'path';
import { cwd } from 'process';
import { readFileSync, accessSync, promises as fsPromises } from 'fs';
import { readFileSync, promises as fsPromises, existsSync } from 'fs';

const { readFile, access } = fsPromises;

Expand Down Expand Up @@ -77,12 +77,7 @@ export class CodeFileLoader implements UniversalLoader<CodeFileLoaderOptions> {
if (isValidPath(pointer)) {
if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
const normalizedFilePath = isAbsolute(pointer) ? pointer : resolve(options.cwd || cwd(), pointer);
try {
accessSync(normalizedFilePath);
return true;
} catch {
return false;
}
return existsSync(normalizedFilePath);
}
}

Expand All @@ -100,7 +95,7 @@ export class CodeFileLoader implements UniversalLoader<CodeFileLoaderOptions> {
const sdl = await gqlPluckFromCodeString(normalizedFilePath, content, options.pluckConfig);

if (sdl) {
return parseSDL({ pointer, sdl, options });
return parseGraphQLSDL(pointer, sdl, options);
}
} catch (e) {
debugLog(`Failed to load schema from code file "${normalizedFilePath}": ${e.message}`);
Expand Down Expand Up @@ -143,7 +138,7 @@ export class CodeFileLoader implements UniversalLoader<CodeFileLoaderOptions> {
const sdl = gqlPluckFromCodeStringSync(normalizedFilePath, content, options.pluckConfig);

if (sdl) {
return parseSDL({ pointer, sdl, options });
return parseGraphQLSDL(pointer, sdl, options);
}
} catch (e) {
debugLog(`Failed to load schema from code file "${normalizedFilePath}": ${e.message}`);
Expand Down Expand Up @@ -176,25 +171,19 @@ export class CodeFileLoader implements UniversalLoader<CodeFileLoaderOptions> {
}
}

function parseSDL({ pointer, sdl, options }: { pointer: string; sdl: string; options: CodeFileLoaderOptions }) {
return parseGraphQLSDL(pointer, sdl, options);
}

function resolveSource(pointer: string, value: any, options: CodeFileLoaderOptions): Source | null {
if (isSchema(value)) {
function resolveSource(pointer: string, value: GraphQLSchema | DocumentNode | string, options: CodeFileLoaderOptions): Source | null {
if (typeof value === 'string') {
return parseGraphQLSDL(pointer, value, options);
} else if (isSchema(value)) {
return {
location: pointer,
rawSDL: printSchemaWithDirectives(value, options),
schema: value,
};
} else if (value?.kind === Kind.DOCUMENT) {
} else if (isDocumentNode(value)) {
return {
location: pointer,
rawSDL: print(value),
document: value,
};
} else if (typeof value === 'string') {
return parseGraphQLSDL(pointer, value, options);
}

return null;
Expand Down

0 comments on commit 982c8f5

Please sign in to comment.