nuxt-graphql-middleware 1.2.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/module.mjs +324 -0
  2. package/dist/plugin.mjs +97 -0
  3. package/{lib/types/module → dist/types}/codegen.d.ts +0 -0
  4. package/dist/types/codegen.d.ts.map +1 -0
  5. package/{lib/types/module → dist/types}/graphqlImport.d.ts +0 -0
  6. package/dist/types/graphqlImport.d.ts.map +1 -0
  7. package/dist/types/index.d.ts +2 -0
  8. package/dist/types/index.d.ts.map +1 -0
  9. package/{lib/types/module/index.d.ts → dist/types/module.d.ts} +5 -4
  10. package/dist/types/module.d.ts.map +1 -0
  11. package/{lib/types/serverMiddleware/index.d.ts → dist/types/serverMiddleware.d.ts} +1 -1
  12. package/dist/types/serverMiddleware.d.ts.map +1 -0
  13. package/{lib/types/plugin/index.d.ts → dist/types/templates/plugin.d.ts} +2 -1
  14. package/dist/types/templates/plugin.d.ts.map +1 -0
  15. package/module.cjs +6 -0
  16. package/package.json +44 -30
  17. package/{types.d.ts → types/index.d.ts} +8 -9
  18. package/lib/cjs/index.js +0 -5
  19. package/lib/cjs/module/codegen.js +0 -84
  20. package/lib/cjs/module/graphqlImport.js +0 -14
  21. package/lib/cjs/module/index.js +0 -177
  22. package/lib/cjs/plugin/index.js +0 -95
  23. package/lib/cjs/serverMiddleware/index.js +0 -113
  24. package/lib/esm/index.js +0 -1
  25. package/lib/esm/module/codegen.js +0 -59
  26. package/lib/esm/module/graphqlImport.js +0 -11
  27. package/lib/esm/module/index.js +0 -170
  28. package/lib/esm/plugin/index.js +0 -91
  29. package/lib/esm/serverMiddleware/index.js +0 -107
  30. package/lib/types/index.d.ts +0 -2
  31. package/lib/types/index.d.ts.map +0 -1
  32. package/lib/types/module/codegen.d.ts.map +0 -1
  33. package/lib/types/module/graphqlImport.d.ts.map +0 -1
  34. package/lib/types/module/index.d.ts.map +0 -1
  35. package/lib/types/plugin/index.d.ts.map +0 -1
  36. package/lib/types/serverMiddleware/index.d.ts.map +0 -1
@@ -1,84 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- var __importDefault = (this && this.__importDefault) || function (mod) {
22
- return (mod && mod.__esModule) ? mod : { "default": mod };
23
- };
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- const path_1 = __importDefault(require("path"));
26
- const cli_1 = require("@graphql-codegen/cli");
27
- const PluginTypescript = __importStar(require("@graphql-codegen/typescript"));
28
- const PluginTypescriptOperations = __importStar(require("@graphql-codegen/typescript-operations"));
29
- const PluginSchemaAst = __importStar(require("@graphql-codegen/schema-ast"));
30
- const typescriptConfig = {
31
- exportFragmentSpreadSubTypes: true,
32
- preResolveTypes: true,
33
- skipTypeNameForRoot: true,
34
- };
35
- function pluginLoader(name) {
36
- if (name === '@graphql-codegen/typescript') {
37
- return Promise.resolve(PluginTypescript);
38
- }
39
- else if (name === '@graphql-codegen/typescript-operations') {
40
- return Promise.resolve(PluginTypescriptOperations);
41
- }
42
- else {
43
- return Promise.resolve(PluginSchemaAst);
44
- }
45
- }
46
- function default_1(graphqlServer, options) {
47
- const schemaPath = path_1.default.resolve(options.schemaOutputPath, 'schema.graphql');
48
- function generateSchema() {
49
- const schema = options.skipSchemaDownload
50
- ? schemaPath
51
- : { [graphqlServer]: options.schemaOptions };
52
- const configSchemaAst = Object.assign(Object.assign({}, typescriptConfig), { sort: true });
53
- return cli_1.generate({
54
- schema,
55
- pluginLoader,
56
- generates: {
57
- [schemaPath]: {
58
- plugins: [{ 'schema-ast': configSchemaAst }],
59
- config: configSchemaAst,
60
- },
61
- [path_1.default.resolve(options.typesOutputPath, 'graphql-schema.d.ts')]: {
62
- plugins: [{ typescript: typescriptConfig }],
63
- config: typescriptConfig,
64
- },
65
- },
66
- }, true);
67
- }
68
- function generateTypes() {
69
- const config = Object.assign(Object.assign({}, typescriptConfig), { onlyOperationTypes: true });
70
- return cli_1.generate({
71
- schema: schemaPath,
72
- pluginLoader,
73
- documents: path_1.default.resolve(options.resolvedQueriesPath, './*.graphql'),
74
- generates: {
75
- [path_1.default.resolve(options.typesOutputPath, 'graphql-operations.d.ts')]: {
76
- plugins: ['typescript', { 'typescript-operations': config }],
77
- config,
78
- },
79
- },
80
- }, true);
81
- }
82
- return { generateSchema, generateTypes };
83
- }
84
- exports.default = default_1;
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const fragmentImport = require('@graphql-fragment-import/lib/inline-imports');
4
- function default_1(path, resolver) {
5
- return fragmentImport(path, {
6
- resolveImport(identifier) {
7
- return resolver(identifier);
8
- },
9
- resolveOptions: {
10
- basedir: './',
11
- },
12
- });
13
- }
14
- exports.default = default_1;
@@ -1,177 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.graphqlMiddleware = void 0;
16
- const path_1 = __importDefault(require("path"));
17
- const fs_1 = __importDefault(require("fs"));
18
- const mkdirp_1 = __importDefault(require("mkdirp"));
19
- const chokidar_1 = __importDefault(require("chokidar"));
20
- const consola_1 = __importDefault(require("consola"));
21
- const serverMiddleware_1 = __importDefault(require("./../serverMiddleware"));
22
- const graphqlImport_1 = __importDefault(require("./graphqlImport"));
23
- const codegen_1 = __importDefault(require("./codegen"));
24
- const logger = consola_1.default.withTag('nuxt-graphql-middleware');
25
- const PLUGIN_PATH = path_1.default.resolve(__dirname, './../plugin/index.js');
26
- var FileType;
27
- (function (FileType) {
28
- FileType["Query"] = "query";
29
- FileType["Mutation"] = "mutation";
30
- })(FileType || (FileType = {}));
31
- function resolveGraphqlFile(file, resolver) {
32
- return fs_1.default.promises
33
- .readFile(file)
34
- .then((buffer) => buffer.toString())
35
- .then((source) => graphqlImport_1.default(source, resolver));
36
- }
37
- function writeSource(dest, type, name, source) {
38
- const fileName = `${type}.${name}.graphql`;
39
- const out = path_1.default.resolve(dest, fileName);
40
- return fs_1.default.promises.writeFile(out, source);
41
- }
42
- function resolveGraphql(files, map, resolver, filesMap, type, outputPath) {
43
- return Promise.all(Object.keys(files).map((name) => {
44
- const filePath = files[name];
45
- const file = resolver(filePath);
46
- return resolveGraphqlFile(file, resolver).then((source) => {
47
- map.set(name, source);
48
- if (outputPath) {
49
- writeSource(outputPath, type, name, source);
50
- }
51
- filesMap.set(file, {
52
- type,
53
- name,
54
- file: filePath,
55
- });
56
- });
57
- }));
58
- }
59
- const graphqlMiddleware = function () {
60
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
61
- return __awaiter(this, void 0, void 0, function* () {
62
- const resolver = this.nuxt.resolver.resolveAlias;
63
- const options = this.options;
64
- const PORT = ((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.server) === null || _b === void 0 ? void 0 : _b.port) || 3000;
65
- const provided = (this.options.graphqlMiddleware ||
66
- {});
67
- const config = {
68
- graphqlServer: provided.graphqlServer || '',
69
- typescript: {
70
- enabled: !!((_c = provided.typescript) === null || _c === void 0 ? void 0 : _c.enabled),
71
- schemaOptions: (_d = provided.typescript) === null || _d === void 0 ? void 0 : _d.schemaOptions,
72
- resolvedQueriesPath: ((_e = provided.typescript) === null || _e === void 0 ? void 0 : _e.resolvedQueriesPath) || provided.outputPath || '',
73
- schemaOutputPath: ((_f = provided.typescript) === null || _f === void 0 ? void 0 : _f.schemaOutputPath) || '~/schema',
74
- typesOutputPath: ((_g = provided.typescript) === null || _g === void 0 ? void 0 : _g.typesOutputPath) || '~/types',
75
- skipSchemaDownload: !!((_h = provided.typescript) === null || _h === void 0 ? void 0 : _h.skipSchemaDownload),
76
- },
77
- endpointNamespace: provided.endpointNamespace || '/__graphql_middleware',
78
- debug: provided.debug || options.dev,
79
- queries: provided.queries || {},
80
- mutations: provided.mutations || {},
81
- outputPath: provided.outputPath || '',
82
- server: provided.server,
83
- plugin: {
84
- enabled: !!((_j = provided.plugin) === null || _j === void 0 ? void 0 : _j.enabled),
85
- cacheInBrowser: !!((_k = provided.plugin) === null || _k === void 0 ? void 0 : _k.cacheInBrowser),
86
- cacheInServer: !!((_l = provided.plugin) === null || _l === void 0 ? void 0 : _l.cacheInServer),
87
- },
88
- };
89
- if ((_m = config.plugin) === null || _m === void 0 ? void 0 : _m.enabled) {
90
- this.addPlugin({
91
- src: PLUGIN_PATH,
92
- options: {
93
- namespace: config.endpointNamespace,
94
- port: PORT,
95
- cacheInBrowser: ((_o = config.plugin) === null || _o === void 0 ? void 0 : _o.cacheInBrowser) ? 'true' : 'false',
96
- cacheInServer: ((_p = config.plugin) === null || _p === void 0 ? void 0 : _p.cacheInServer) ? 'true' : 'false',
97
- },
98
- });
99
- }
100
- const fileMap = new Map();
101
- const queries = new Map();
102
- const mutations = new Map();
103
- const outputPath = config.outputPath ? resolver(config.outputPath) : '';
104
- yield mkdirp_1.default(outputPath);
105
- const schemaOutputPath = resolver((_q = config.typescript) === null || _q === void 0 ? void 0 : _q.schemaOutputPath);
106
- const typesOutputPath = resolver((_r = config.typescript) === null || _r === void 0 ? void 0 : _r.typesOutputPath);
107
- const { generateSchema, generateTypes } = codegen_1.default(config.graphqlServer, {
108
- resolvedQueriesPath: config.outputPath,
109
- schemaOptions: (_s = config.typescript) === null || _s === void 0 ? void 0 : _s.schemaOptions,
110
- skipSchemaDownload: (_t = config.typescript) === null || _t === void 0 ? void 0 : _t.skipSchemaDownload,
111
- schemaOutputPath,
112
- typesOutputPath,
113
- });
114
- if ((_u = config.typescript) === null || _u === void 0 ? void 0 : _u.enabled) {
115
- if (!outputPath) {
116
- throw new Error('TypeScript enabled, but no outputPath given.');
117
- }
118
- yield mkdirp_1.default(schemaOutputPath);
119
- yield generateSchema();
120
- }
121
- function build() {
122
- logger.log('Building GraphQL files...');
123
- return Promise.all([
124
- resolveGraphql(config.queries, queries, resolver, fileMap, FileType.Query, outputPath),
125
- resolveGraphql(config.mutations, mutations, resolver, fileMap, FileType.Mutation, outputPath),
126
- ]).then(() => {
127
- var _a;
128
- logger.success('Finished building GraphQL files');
129
- if ((_a = config.typescript) === null || _a === void 0 ? void 0 : _a.enabled) {
130
- return generateTypes().then(() => {
131
- logger.success('Finished generating GraphQL TypeScript files.');
132
- });
133
- }
134
- });
135
- }
136
- function watchFiles() {
137
- const ignored = ['node_modules', '.nuxt'];
138
- if (config.outputPath) {
139
- ignored.push(config.outputPath);
140
- }
141
- const filesWatcher = chokidar_1.default.watch('./**/*.graphql', {
142
- ignoreInitial: true,
143
- ignored,
144
- });
145
- if (filesWatcher) {
146
- logger.info('Watching for query changes');
147
- filesWatcher.on('change', () => {
148
- build();
149
- });
150
- }
151
- return filesWatcher;
152
- }
153
- let watcher;
154
- if (this.nuxt.options.dev) {
155
- this.nuxt.hook('build:done', () => {
156
- watcher = watchFiles();
157
- });
158
- this.nuxt.hook('close', () => {
159
- if (watcher) {
160
- watcher.close();
161
- watcher = undefined;
162
- }
163
- });
164
- }
165
- build().then(() => {
166
- if (options.debug) {
167
- logger.info('Available queries and mutations:');
168
- console.table(Array.from(fileMap.entries()).map(([_key, value]) => value));
169
- }
170
- });
171
- this.addServerMiddleware({
172
- path: config.endpointNamespace,
173
- handler: serverMiddleware_1.default(config.graphqlServer, queries, mutations, config.server),
174
- });
175
- });
176
- };
177
- exports.graphqlMiddleware = graphqlMiddleware;
@@ -1,95 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GraphqlMiddlewarePlugin = void 0;
4
- const IS_DEV = process.env.NODE_ENV === 'development';
5
- function log(action, path, message) {
6
- if (IS_DEV) {
7
- console.log(`[API - ${action}] ${message}: ${path}`);
8
- }
9
- }
10
- class GraphqlMiddlewarePlugin {
11
- constructor(baseURL, headers, useCache, context) {
12
- this.baseURL = baseURL;
13
- this.headers = headers || {};
14
- this.context = context;
15
- if (useCache) {
16
- this.cache = new Map();
17
- }
18
- }
19
- getPluginHeaderValue() {
20
- var _a, _b;
21
- return {
22
- 'Nuxt-Graphql-Middleware-Route': ((_b = (_a = this.context) === null || _a === void 0 ? void 0 : _a.route) === null || _b === void 0 ? void 0 : _b.fullPath) || '',
23
- };
24
- }
25
- beforeRequest(fn) {
26
- this.beforeRequestFn = fn;
27
- }
28
- query(name, variables, headers = {}) {
29
- var _a;
30
- const params = new URLSearchParams({
31
- name,
32
- variables: JSON.stringify(variables || {}),
33
- });
34
- const url = this.baseURL + '/query?' + params.toString();
35
- if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.has(url)) {
36
- log('query', url, 'Loading from cache');
37
- return Promise.resolve(this.cache.get(url));
38
- }
39
- log('query', url, 'Fetching');
40
- let fetchOptions = {
41
- method: 'GET',
42
- credentials: 'include',
43
- headers: Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), this.headers), this.getPluginHeaderValue()),
44
- };
45
- if (this.beforeRequestFn) {
46
- fetchOptions = this.beforeRequestFn(this.context, fetchOptions);
47
- }
48
- return fetch(url, fetchOptions)
49
- .then((response) => {
50
- if (response.ok) {
51
- return response.json();
52
- }
53
- throw new Error('Server Error');
54
- })
55
- .then((data) => {
56
- var _a;
57
- if (this.cache && this.cache.size > 30) {
58
- const key = this.cache.keys().next().value;
59
- this.cache.delete(key);
60
- }
61
- (_a = this.cache) === null || _a === void 0 ? void 0 : _a.set(url, data);
62
- return data;
63
- });
64
- }
65
- mutate(name, variables, headers = {}) {
66
- const params = new URLSearchParams({
67
- name,
68
- });
69
- let fetchOptions = {
70
- method: 'POST',
71
- credentials: 'include',
72
- headers: Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), this.headers), this.getPluginHeaderValue()),
73
- body: JSON.stringify(variables),
74
- };
75
- if (this.beforeRequestFn) {
76
- fetchOptions = this.beforeRequestFn(this.context, fetchOptions);
77
- }
78
- return fetch(this.baseURL + '/mutate?' + params.toString(), fetchOptions).then((response) => response.json());
79
- }
80
- }
81
- exports.GraphqlMiddlewarePlugin = GraphqlMiddlewarePlugin;
82
- const graphqlMiddlewarePlugin = (context, inject) => {
83
- var _a, _b;
84
- const namespace = "<%= options.namespace || '' %>";
85
- const port = ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.NUXT_PORT) || '<%= options.port %>';
86
- const cacheInBrowser = "<%= options.cacheInBrowser || '' %>" === 'true';
87
- const cacheInServer = "<%= options.cacheInServer || '' %>" === 'true';
88
- let baseURL = namespace;
89
- if (process.server) {
90
- baseURL = 'http://0.0.0.0:' + port + namespace;
91
- }
92
- const useCache = (process.server && cacheInServer) || (process.client && cacheInBrowser);
93
- inject('graphql', new GraphqlMiddlewarePlugin(baseURL, (_b = context.req) === null || _b === void 0 ? void 0 : _b.headers, useCache, context));
94
- };
95
- exports.default = graphqlMiddlewarePlugin;
@@ -1,113 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const express_1 = __importDefault(require("express"));
16
- const graphql_request_1 = require("graphql-request");
17
- function getVariables(vars) {
18
- try {
19
- const variables = JSON.parse(vars);
20
- return variables;
21
- }
22
- catch (error) {
23
- return {};
24
- }
25
- }
26
- function buildHeaders(req, name, type, config) {
27
- var _a;
28
- if (config === null || config === void 0 ? void 0 : config.buildHeaders) {
29
- return config.buildHeaders(req, name, type);
30
- }
31
- if ((_a = config === null || config === void 0 ? void 0 : config.fetchOptions) === null || _a === void 0 ? void 0 : _a.headers) {
32
- return config.fetchOptions.headers;
33
- }
34
- return {};
35
- }
36
- function createServerMiddleware(graphqlServer, queries, mutations, config) {
37
- const app = express_1.default();
38
- app.use(express_1.default.json());
39
- const clients = new Map();
40
- function getClient(endpoint) {
41
- if (!clients.has(endpoint)) {
42
- const client = new graphql_request_1.GraphQLClient(endpoint);
43
- clients.set(endpoint, client);
44
- }
45
- return clients.get(endpoint);
46
- }
47
- function getEndpoint(req) {
48
- if (config === null || config === void 0 ? void 0 : config.buildEndpoint) {
49
- return config.buildEndpoint(req);
50
- }
51
- return graphqlServer;
52
- }
53
- if (config === null || config === void 0 ? void 0 : config.middleware) {
54
- app.use(config.middleware);
55
- }
56
- function query(req, res) {
57
- return __awaiter(this, void 0, void 0, function* () {
58
- const name = req.query.name;
59
- if (!name || !queries.has(name)) {
60
- res.status(404).send();
61
- return;
62
- }
63
- try {
64
- const headers = buildHeaders(req, name, 'query', config);
65
- const variables = getVariables(req.query.variables);
66
- const query = queries.get(name);
67
- const endpoint = getEndpoint(req);
68
- const client = getClient(endpoint);
69
- const response = yield client.rawRequest(query, variables, headers);
70
- if (config === null || config === void 0 ? void 0 : config.onQueryResponse) {
71
- return config.onQueryResponse(response, req, res);
72
- }
73
- return res.json(response.data);
74
- }
75
- catch (e) {
76
- if (config === null || config === void 0 ? void 0 : config.onQueryError) {
77
- return config.onQueryError(e, req, res);
78
- }
79
- return res.status(500).send();
80
- }
81
- });
82
- }
83
- function mutate(req, res) {
84
- return __awaiter(this, void 0, void 0, function* () {
85
- const name = req.query.name;
86
- if (!name || !mutations.has(name)) {
87
- res.status(404).send();
88
- return;
89
- }
90
- const mutation = mutations.get(name);
91
- try {
92
- const headers = buildHeaders(req, name, 'mutation', config);
93
- const endpoint = getEndpoint(req);
94
- const client = getClient(endpoint);
95
- const response = yield client.request(mutation, req.body, headers);
96
- if (config === null || config === void 0 ? void 0 : config.onMutationResponse) {
97
- return config.onMutationResponse(response, req, res);
98
- }
99
- return res.json(response);
100
- }
101
- catch (error) {
102
- if (config === null || config === void 0 ? void 0 : config.onMutationError) {
103
- return config.onMutationError(error, req, res);
104
- }
105
- return res.status(500).send();
106
- }
107
- });
108
- }
109
- app.get('/query', query);
110
- app.post('/mutate', mutate);
111
- return app;
112
- }
113
- exports.default = createServerMiddleware;
package/lib/esm/index.js DELETED
@@ -1 +0,0 @@
1
- export { graphqlMiddleware as default } from './module';
@@ -1,59 +0,0 @@
1
- import path from 'path';
2
- import { generate } from '@graphql-codegen/cli';
3
- import * as PluginTypescript from '@graphql-codegen/typescript';
4
- import * as PluginTypescriptOperations from '@graphql-codegen/typescript-operations';
5
- import * as PluginSchemaAst from '@graphql-codegen/schema-ast';
6
- const typescriptConfig = {
7
- exportFragmentSpreadSubTypes: true,
8
- preResolveTypes: true,
9
- skipTypeNameForRoot: true,
10
- };
11
- function pluginLoader(name) {
12
- if (name === '@graphql-codegen/typescript') {
13
- return Promise.resolve(PluginTypescript);
14
- }
15
- else if (name === '@graphql-codegen/typescript-operations') {
16
- return Promise.resolve(PluginTypescriptOperations);
17
- }
18
- else {
19
- return Promise.resolve(PluginSchemaAst);
20
- }
21
- }
22
- export default function (graphqlServer, options) {
23
- const schemaPath = path.resolve(options.schemaOutputPath, 'schema.graphql');
24
- function generateSchema() {
25
- const schema = options.skipSchemaDownload
26
- ? schemaPath
27
- : { [graphqlServer]: options.schemaOptions };
28
- const configSchemaAst = Object.assign(Object.assign({}, typescriptConfig), { sort: true });
29
- return generate({
30
- schema,
31
- pluginLoader,
32
- generates: {
33
- [schemaPath]: {
34
- plugins: [{ 'schema-ast': configSchemaAst }],
35
- config: configSchemaAst,
36
- },
37
- [path.resolve(options.typesOutputPath, 'graphql-schema.d.ts')]: {
38
- plugins: [{ typescript: typescriptConfig }],
39
- config: typescriptConfig,
40
- },
41
- },
42
- }, true);
43
- }
44
- function generateTypes() {
45
- const config = Object.assign(Object.assign({}, typescriptConfig), { onlyOperationTypes: true });
46
- return generate({
47
- schema: schemaPath,
48
- pluginLoader,
49
- documents: path.resolve(options.resolvedQueriesPath, './*.graphql'),
50
- generates: {
51
- [path.resolve(options.typesOutputPath, 'graphql-operations.d.ts')]: {
52
- plugins: ['typescript', { 'typescript-operations': config }],
53
- config,
54
- },
55
- },
56
- }, true);
57
- }
58
- return { generateSchema, generateTypes };
59
- }
@@ -1,11 +0,0 @@
1
- const fragmentImport = require('@graphql-fragment-import/lib/inline-imports');
2
- export default function (path, resolver) {
3
- return fragmentImport(path, {
4
- resolveImport(identifier) {
5
- return resolver(identifier);
6
- },
7
- resolveOptions: {
8
- basedir: './',
9
- },
10
- });
11
- }