Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Added transfer-field transform #3041

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions packages/transforms/transfer-field/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "@graphql-mesh/transform-transform-field",
"version": "0.0.0",
"sideEffects": false,
"main": "dist/index.js",
"module": "dist/index.mjs",
"typings": "dist/index.d.ts",
"typescript": {
"definition": "dist/index.d.ts"
},
"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.mjs"
},
"./*": {
"require": "./dist/*.js",
"import": "./dist/*.mjs"
}
},
"license": "MIT",
"peerDependencies": {
"graphql": "*"
},
"dependencies": {
"@graphql-mesh/types": "0.53.0",
"@graphql-tools/utils": "8.5.0"
},
"publishConfig": {
"access": "public",
"directory": "dist"
},
"devDependencies": {
"@graphql-mesh/cache-inmemory-lru": "^0.5.25",
"@graphql-tools/schema": "8.3.0",
"graphql-subscriptions": "1.2.1"
}
}
90 changes: 90 additions & 0 deletions packages/transforms/transfer-field/src/bareTransferField.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { MeshTransform, MeshTransformOptions, YamlConfig } from '@graphql-mesh/types';
import { appendObjectFields, pruneSchema, removeObjectFields } from '@graphql-tools/utils';
import { GraphQLFieldConfigMap, GraphQLSchema } from 'graphql';

type FieldConfig = YamlConfig.TransferFieldTransformFieldConfigObject & {
removeObjectFieldsTestFn: (fieldName: string) => boolean;
};

export default class TransferFieldTransform implements MeshTransform {
noWrap = true;

private transfers: FieldConfig[] = [];

constructor(options: MeshTransformOptions<YamlConfig.TransferFieldTransformConfig>) {
const { config } = options;

const {
defaults: {
useRegExp: useRegExpDefault = false,
regExpFlags: regExpFlagsDefault = undefined,
action: actionDefault = 'move',
} = {},
fields: fieldConfigs,
} = config;

for (const fieldConfig of fieldConfigs) {
const {
from,
to,
useRegExp = useRegExpDefault,
regExpFlags = regExpFlagsDefault,
action = actionDefault,
} = fieldConfig;

const fieldConfigWithDefaults: FieldConfig = {
from,
to,
useRegExp,
regExpFlags,
action,
removeObjectFieldsTestFn: useRegExp
? fieldName => new RegExp(from.field, regExpFlags).test(fieldName)
: fieldName => fieldName === from.field,
};

this.transfers.push(fieldConfigWithDefaults);
}
}

transformSchema(schema: GraphQLSchema) {
let transformedSchema = schema;

for (const fieldConfig of this.transfers) {
const {
from: { type: fromTypeName, field: fromFieldName },
to: { type: toTypeName, field: toFieldName },
useRegExp,
regExpFlags,
action,
removeObjectFieldsTestFn,
} = fieldConfig;

const [schemaWithoutFields, sourceFieldConfigMap] = removeObjectFields(
transformedSchema,
fromTypeName,
removeObjectFieldsTestFn
);

if (action === 'move') {
transformedSchema = schemaWithoutFields;
}

const sourceFieldNames = Object.keys(sourceFieldConfigMap) as string[];

const appendFieldConfigMap: GraphQLFieldConfigMap<any, any> = {};
for (const sourceFieldName of sourceFieldNames) {
const targetFieldName = useRegExp
? sourceFieldName.replace(new RegExp(fromFieldName, regExpFlags), toFieldName)
: toFieldName;

const sourceField = sourceFieldConfigMap[sourceFieldName];
appendFieldConfigMap[targetFieldName] = sourceField;
}

transformedSchema = appendObjectFields(transformedSchema, toTypeName, appendFieldConfigMap);
}

return pruneSchema(transformedSchema);
}
}
9 changes: 9 additions & 0 deletions packages/transforms/transfer-field/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { MeshTransform, MeshTransformOptions, YamlConfig } from '@graphql-mesh/types';
import BareTransferField from './bareTransferField';
import WrapTransferField from './wrapTransferField';

export default function HoistFieldTransform(
options: MeshTransformOptions<YamlConfig.TransferFieldTransformConfig>
): MeshTransform {
return options.config.mode === 'bare' ? new BareTransferField(options) : new WrapTransferField(options);
}
9 changes: 9 additions & 0 deletions packages/transforms/transfer-field/src/wrapTransferField.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { MeshTransform, MeshTransformOptions, YamlConfig } from '@graphql-mesh/types';

export default class WrapTransferField implements MeshTransform {
noWrap = false;

constructor(options: MeshTransformOptions<YamlConfig.TransferFieldTransformConfig>) {
throw new Error('Not implemented');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`transform-field should copy field to different type - regex 1`] = `
"type Query {
dummy: String

\\"\\"\\"Retrieve a list of Books\\"\\"\\"
books(maxResults: Int, orderBy: String): [Book]
}

type Mutation {
\\"\\"\\"Retrieve a list of Books\\"\\"\\"
books(maxResults: Int, orderBy: String): [Book]
}

type Book {
title: String!
author: Author!
code: String
}

type Author {
name: String!
age: Int!
}
"
`;

exports[`transform-field should move field to different type - no regex 1`] = `
"type Query {
dummy: String

\\"\\"\\"Retrieve a list of Books\\"\\"\\"
books(maxResults: Int, orderBy: String): [Book]
}

type Book {
title: String!
author: Author!
code: String
}

type Author {
name: String!
age: Int!
}
"
`;

exports[`transform-field should move field to different type - regex 1`] = `
"type Query {
dummy: String

\\"\\"\\"Retrieve a list of Books\\"\\"\\"
books(maxResults: Int, orderBy: String): [Book]
}

type Book {
title: String!
author: Author!
code: String
}

type Author {
name: String!
age: Int!
}
"
`;
154 changes: 154 additions & 0 deletions packages/transforms/transfer-field/test/bareTransferField.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { join } from 'path';
import { execute, parse, printSchema, GraphQLObjectType } from 'graphql';
import InMemoryLRUCache from '@graphql-mesh/cache-inmemory-lru';
import { MeshPubSub } from '@graphql-mesh/types';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { PubSub } from 'graphql-subscriptions';

import TransferFieldTransform from '../src/bareTransferField';

describe('transform-field', () => {
const mockQueryBooks = jest.fn().mockImplementation(() => ({ books: [{ title: 'abc' }, { title: 'def' }] }));
const mockBooksApiResponseBooks = jest.fn().mockImplementation(() => [{ title: 'ghi' }, { title: 'lmn' }]);

const schemaDefs = /* GraphQL */ `
type Query {
dummy: String
}

type Mutation {
"""
Retrieve a list of Books
"""
books(maxResults: Int, orderBy: String): [Book]
}

type Book {
title: String!
author: Author!
code: String
}

type Author {
name: String!
age: Int!
}
`;
let cache: InMemoryLRUCache;
let pubsub: MeshPubSub;
const baseDir: string = undefined;

beforeEach(() => {
jest.clearAllMocks();
});

afterEach(() => {
cache = new InMemoryLRUCache();
pubsub = new PubSub();
});

it('should move field to different type - no regex', async () => {
const transform = new TransferFieldTransform({
config: {
mode: 'bare',
fields: [
{
from: {
type: 'Mutation',
field: 'books',
},
to: {
type: 'Query',
field: 'books',
},
},
],
},
cache,
pubsub,
baseDir,
apiName: '',
syncImportFn: require,
});
const schema = makeExecutableSchema({
typeDefs: schemaDefs,
});
const transformedSchema = transform.transformSchema(schema);

expect(transformedSchema.getType('Mutation')).toBeUndefined();
expect((transformedSchema.getType('Query') as GraphQLObjectType).getFields().books.type.toString()).toBe('[Book]');
expect(printSchema(transformedSchema)).toMatchSnapshot();
});

it('should move field to different type - regex', async () => {
const transform = new TransferFieldTransform({
config: {
mode: 'bare',
fields: [
{
from: {
type: 'Mutation',
field: '(.*)',
},
to: {
type: 'Query',
field: '$1',
},
useRegExp: true,
},
],
},
cache,
pubsub,
baseDir,
apiName: '',
syncImportFn: require,
});
const schema = makeExecutableSchema({
typeDefs: schemaDefs,
});
const transformedSchema = transform.transformSchema(schema);

expect(transformedSchema.getType('Mutation')).toBeUndefined();
expect((transformedSchema.getType('Query') as GraphQLObjectType).getFields().books.type.toString()).toBe('[Book]');
expect(printSchema(transformedSchema)).toMatchSnapshot();
});

it('should copy field to different type - regex', async () => {
const transform = new TransferFieldTransform({
config: {
mode: 'bare',
fields: [
{
from: {
type: 'Mutation',
field: '(.*)',
},
to: {
type: 'Query',
field: '$1',
},
useRegExp: true,
action: 'copy',
},
],
},
cache,
pubsub,
baseDir,
apiName: '',
syncImportFn: require,
});
const schema = makeExecutableSchema({
typeDefs: schemaDefs,
});
const transformedSchema = transform.transformSchema(schema);

expect(transformedSchema.getType('Mutation')).toBeDefined();
expect((transformedSchema.getType('Mutation') as GraphQLObjectType).getFields().books.type.toString()).toBe(
'[Book]'
);
expect((transformedSchema.getType('Query') as GraphQLObjectType).getFields().books.type.toString()).toBe('[Book]');
expect(printSchema(transformedSchema)).toMatchSnapshot();
});
});
Loading