1 | import { addMocksToSchema } from '@graphql-tools/mock';
|
2 | import * as faker from 'faker';
|
3 | import { fake } from 'faker';
|
4 | import { loadFromModuleExportExpressionSync } from '@graphql-mesh/utils';
|
5 |
|
6 | class MockingTransform {
|
7 | constructor(options) {
|
8 | this.options = options;
|
9 | }
|
10 | transformSchema(schema) {
|
11 | const { config } = this.options;
|
12 | const configIf = 'if' in config ? config.if : true;
|
13 | if (configIf) {
|
14 | const mocks = {};
|
15 | if (config.mocks) {
|
16 | for (const fieldConfig of config.mocks) {
|
17 | const fieldConfigIf = 'if' in fieldConfig ? fieldConfig.if : true;
|
18 | if (fieldConfigIf) {
|
19 | const [typeName, fieldName] = fieldConfig.apply.split('.');
|
20 | mocks[typeName] = mocks[typeName] || (() => ({}));
|
21 | if (fieldName) {
|
22 | if (fieldConfig.faker) {
|
23 | const prevFn = mocks[typeName];
|
24 | let fakerFn;
|
25 | const [service, method] = fieldConfig.faker.split('.');
|
26 | if (service in faker) {
|
27 | fakerFn = () => faker[service][method]();
|
28 | }
|
29 | else {
|
30 | fakerFn = () => fake(fieldConfig.faker || '');
|
31 | }
|
32 | mocks[typeName] = (...args) => {
|
33 | const prevObj = prevFn(...args);
|
34 | prevObj[fieldName] = fakerFn;
|
35 | return prevObj;
|
36 | };
|
37 | }
|
38 | else if (fieldConfig.custom) {
|
39 | const exportedVal = loadFromModuleExportExpressionSync(fieldConfig.custom);
|
40 | const prevFn = mocks[typeName];
|
41 | mocks[typeName] = (...args) => {
|
42 | const prevObj = prevFn(...args);
|
43 | prevObj[fieldName] = typeof exportedVal === 'function' ? exportedVal : () => exportedVal;
|
44 | return prevObj;
|
45 | };
|
46 | }
|
47 | }
|
48 | else {
|
49 | if (fieldConfig.faker) {
|
50 | let fakerFn;
|
51 | const [service, method] = fieldConfig.faker.split('.');
|
52 | if (service in faker) {
|
53 | fakerFn = () => faker[service][method]();
|
54 | }
|
55 | else {
|
56 | fakerFn = () => fake(fieldConfig.faker || '');
|
57 | }
|
58 | mocks[typeName] = fakerFn;
|
59 | }
|
60 | else if (fieldConfig.custom) {
|
61 | const [moduleName, exportName] = fieldConfig.custom.split('#');
|
62 | const m = require(moduleName);
|
63 | const exportedVal = m[exportName] || (m.default && m.default[exportName]);
|
64 | mocks[typeName] = typeof exportedVal === 'function' ? exportedVal : () => exportedVal;
|
65 | }
|
66 | }
|
67 | }
|
68 | }
|
69 | }
|
70 | return addMocksToSchema({
|
71 | schema,
|
72 | mocks,
|
73 | preserveResolvers: config === null || config === void 0 ? void 0 : config.preserveResolvers,
|
74 | });
|
75 | }
|
76 | return schema;
|
77 | }
|
78 | }
|
79 |
|
80 | export default MockingTransform;
|
81 |
|