UNPKG

2.32 kBPlain TextView Raw
1import { CompilerContext } from "apollo-codegen-core/lib/compiler";
2import Dependencies, { FragmentDependency } from "./dependencies";
3import {
4 ImportDeclaration,
5 importDeclaration,
6 stringLiteral,
7 ImportSpecifier,
8 importSpecifier,
9 Identifier,
10 identifier
11} from "@babel/types";
12import { stringIdentifier } from "./types";
13import { relativePath, outputPath } from "./paths";
14import compact from "./compact";
15
16const stringImportSpecifier = (fragmentName: string): ImportSpecifier =>
17 importSpecifierWithIdentifier(stringIdentifier(fragmentName));
18
19const importSpecifierWithIdentifier = (
20 identifier: Identifier
21): ImportSpecifier => importSpecifier(identifier, identifier);
22
23const importDeclarationForFragmentDependency = (
24 fragmentDependency: FragmentDependency,
25 context: CompilerContext,
26 filePath: string
27): ImportDeclaration =>
28 importDeclaration(
29 compact(
30 fragmentDependency.importType &&
31 importSpecifierWithIdentifier(identifier(fragmentDependency.name)),
32 fragmentDependency.importString &&
33 stringImportSpecifier(fragmentDependency.name),
34 fragmentDependency.importType &&
35 !fragmentDependency.importString &&
36 importSpecifierWithIdentifier(
37 identifier(`is${fragmentDependency.name}`)
38 )
39 ),
40 stringLiteral(
41 relativePath(
42 filePath,
43 outputPath(
44 fragmentDependency.name,
45 context.fragments[fragmentDependency.name].filePath
46 )
47 )
48 )
49 );
50
51const importDeclarationForGlobalDependencies = (
52 dependencies: string[],
53 relativeGlobalSourcePath: string
54): ImportDeclaration =>
55 importDeclaration(
56 dependencies.map(dependency =>
57 importSpecifierWithIdentifier(identifier(dependency))
58 ),
59 stringLiteral(relativeGlobalSourcePath)
60 );
61
62export default (
63 dependencies: Dependencies,
64 outputPath: string,
65 globalSourcePath: string,
66 context: CompilerContext
67): ImportDeclaration[] =>
68 compact(
69 dependencies.global.length > 0 &&
70 importDeclarationForGlobalDependencies(
71 dependencies.global,
72 relativePath(outputPath, globalSourcePath)
73 ),
74 ...dependencies.fragments.map(fragmentDependency =>
75 importDeclarationForFragmentDependency(
76 fragmentDependency,
77 context,
78 outputPath
79 )
80 )
81 );