Skip to content

Commit

Permalink
ensure indent is covered via test (#3162)
Browse files Browse the repository at this point in the history
* ensure indent is covered

* allow providing config via constructor

* fix: ensure next loader will be used if first one does not yield a result
  • Loading branch information
n1ru4l authored Jul 7, 2021
1 parent ce9c398 commit bbb5746
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 21 deletions.
5 changes: 5 additions & 0 deletions .changeset/metal-apes-sell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-tools/code-file-loader': minor
---

allow supplying config via constructor
11 changes: 9 additions & 2 deletions packages/load/src/load-typedefs/load-file.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Source, Maybe } from '@graphql-tools/utils';
import { Source, Maybe, isSome } from '@graphql-tools/utils';
import { env } from 'process';
import { LoadTypedefsOptions } from '../load-typedefs';

Expand All @@ -15,6 +15,9 @@ export async function loadFile(pointer: string, options: LoadTypedefsOptions): P

if (canLoad) {
const loadedValue = await loader.load(pointer, options);
if (!isSome(loadedValue) || loadedValue.length === 0) {
continue;
}
return loadedValue;
}
} catch (error) {
Expand All @@ -41,7 +44,11 @@ export function loadFileSync(pointer: string, options: LoadTypedefsOptions): May

if (canLoad) {
// We check for the existence so it is okay to force non null
return loader.loadSync!(pointer, options);
const loadedValue = loader.loadSync!(pointer, options);
if (!isSome(loadedValue) || loadedValue.length === 0) {
continue;
}
return loadedValue;
}
} catch (error) {
if (env['DEBUG']) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,5 +133,12 @@ describe('documentsFromGlob', () => {
});
expect(result.length).toBe(1);
});
test(`should try next loader if first one fails`, async () => {
const glob = join(__dirname, './test-with-brackets/', '**/*.ts');
const result = await load(glob, {
loaders: [new GraphQLFileLoader(), new CodeFileLoader()],
});
expect(result.length).toBe(1);
})
})
});
29 changes: 25 additions & 4 deletions packages/loaders/code-file/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,19 @@ import { createRequire } from 'module';

const { readFile, access } = fsPromises;

export type CodeFileLoaderConfig = {
pluckConfig?: GraphQLTagPluckOptions;
noPluck?: boolean;
noRequire?: boolean;
};

/**
* Additional options for loading from a code file
*/
export type CodeFileLoaderOptions = {
require?: string | string[];
pluckConfig?: GraphQLTagPluckOptions;
noPluck?: boolean;
noRequire?: boolean;
} & BaseLoaderOptions;
} & CodeFileLoaderConfig &
BaseLoaderOptions;

const FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.vue'];

Expand All @@ -57,11 +61,21 @@ function createGlobbyOptions(options: CodeFileLoaderOptions): GlobbyOptions {
* Supported extensions include: `.ts`, `.tsx`, `.js`, `.jsx`, `.vue`
*/
export class CodeFileLoader implements Loader<CodeFileLoaderOptions> {
private config: CodeFileLoaderConfig;
constructor(config?: CodeFileLoaderConfig) {
this.config = config ?? {};
}

private getMergedOptions(options: CodeFileLoaderOptions): CodeFileLoaderOptions {
return { ...this.config, ...options };
}

loaderId(): string {
return 'code-file';
}

async canLoad(pointer: string, options: CodeFileLoaderOptions): Promise<boolean> {
options = this.getMergedOptions(options);
if (isGlob(pointer)) {
// FIXME: parse to find and check the file extensions?
return true;
Expand All @@ -83,6 +97,7 @@ export class CodeFileLoader implements Loader<CodeFileLoaderOptions> {
}

canLoadSync(pointer: string, options: CodeFileLoaderOptions): boolean {
options = this.getMergedOptions(options);
if (isGlob(pointer)) {
// FIXME: parse to find and check the file extensions?
return true;
Expand All @@ -99,16 +114,19 @@ export class CodeFileLoader implements Loader<CodeFileLoaderOptions> {
}

async resolveGlobs(glob: string, options: CodeFileLoaderOptions) {
options = this.getMergedOptions(options);
const ignores = asArray(options.ignore || []);
return globby([glob, ...ignores.map(v => `!(${v})`).map(v => unixify(v))], createGlobbyOptions(options));
}

resolveGlobsSync(glob: string, options: CodeFileLoaderOptions) {
options = this.getMergedOptions(options);
const ignores = asArray(options.ignore || []);
return globby.sync([glob, ...ignores.map(v => `!(${v})`).map(v => unixify(v))], createGlobbyOptions(options));
}

async load(pointer: string, options: CodeFileLoaderOptions): Promise<Source[] | null> {
options = this.getMergedOptions(options);
if (isGlob(pointer)) {
const resolvedPaths = await this.resolveGlobs(pointer, options);
const finalResult: Source[] = [];
Expand All @@ -127,6 +145,7 @@ export class CodeFileLoader implements Loader<CodeFileLoaderOptions> {
}

loadSync(pointer: string, options: CodeFileLoaderOptions): Source[] | null {
options = this.getMergedOptions(options);
if (isGlob(pointer)) {
const resolvedPaths = this.resolveGlobsSync(pointer, options);
const finalResult: Source[] = [];
Expand All @@ -143,6 +162,7 @@ export class CodeFileLoader implements Loader<CodeFileLoaderOptions> {
}

async handleSinglePath(location: string, options: CodeFileLoaderOptions): Promise<Source[] | null> {
options = this.getMergedOptions(options);
const normalizedFilePath = ensureAbsolutePath(location, options);

const errors: Error[] = [];
Expand Down Expand Up @@ -192,6 +212,7 @@ export class CodeFileLoader implements Loader<CodeFileLoaderOptions> {
}

handleSinglePathSync(location: string, options: CodeFileLoaderOptions): Source[] | null {
options = this.getMergedOptions(options);
const normalizedFilePath = ensureAbsolutePath(location, options);

const errors: Error[] = [];
Expand Down
61 changes: 46 additions & 15 deletions packages/loaders/code-file/tests/load-from-code-file.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,30 +117,61 @@ describe('loadFromCodeFileSync', () => {
it('should support loading many in same file', () => {
const loaded = loader.loadSync('./test-files/multiple-from-file.ts', {
cwd: __dirname,
pluckConfig: {
skipIndent: true,
},
});
expect(loaded?.length).toEqual(3);
expect(loaded?.[0].rawSDL).toBeDefined();
expect(loaded?.[0].rawSDL).toMatchInlineSnapshot(`
"query Foo {
Tweets {
id
"
query Foo {
Tweets {
id
}
}
}"
"
`);
expect(loaded?.[1].rawSDL).toBeDefined();
expect(loaded?.[1].rawSDL).toMatchInlineSnapshot(`
"fragment Lel on Tweet {
id
body
}"
`);
"
fragment Lel on Tweet {
id
body
}
"
`);
expect(loaded?.[2].rawSDL).toBeDefined();
expect(loaded?.[2].rawSDL).toMatchInlineSnapshot(`
"query Bar {
Tweets {
...Lel
}
}"
`);
"
query Bar {
Tweets {
...Lel
}
}
"
`);
});

it('can inherit config options from constructor', () => {
const loader = new CodeFileLoader({
pluckConfig: {
skipIndent: true
}
})
const loaded = loader.loadSync('./test-files/multiple-from-file.ts', {
cwd: __dirname,
});
expect(loaded?.length).toEqual(3);
expect(loaded?.[0].rawSDL).toBeDefined();
expect(loaded?.[0].rawSDL).toMatchInlineSnapshot(`
"
query Foo {
Tweets {
id
}
}
"
`);
})
});

0 comments on commit bbb5746

Please sign in to comment.