UNPKG

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