The type-graphql decorator to transform arguments. Contains the most used transformers.
Install the package using the following command:
yarn add @os-team/graphql-transformers
It is assumed that the type-graphql
library is already installed.
For example, we have the fox entity and 2 files: CreateFoxInput.ts
and FoxResolver.ts
.
import { Field, InputType } from 'type-graphql';
import { trim, toLowerCase } from '@os-team/graphql-transformers';
@InputType()
class CreateFoxInput {
@Field()
name!: string;
}
export const createFoxTransformers = {
name: [trim, toLowerCase],
};
export default CreateFoxInput;
import { Arg, Mutation, Resolver } from 'type-graphql';
import { TransformArgs } from '@os-team/graphql-transformers';
import Fox from '../../entities/Fox';
import CreateFoxInput, { createFoxTransformers } from './CreateFoxInput';
@Resolver(() => Fox)
class FoxResolver {
@TransformArgs(createFoxTransformers, { arg: 'input' })
@Mutation(() => Fox)
async createFox(@Arg('input') input: CreateFoxInput): Promise<Fox> {
// The implementation
}
}
export default FoxResolver;
If you did not specify the arg
parameter, the @TransformArgs
decorator will transform all the arguments.
It can be useful, for example, if you want to transform the connection arguments.
import { Args, Query, Resolver } from 'type-graphql';
import { TransformArgs } from '@os-team/graphql-transformers';
import { ConnectionArgs, createConnectionType } from '@os-team/graphql-utils';
import Fox from '../../entities/Fox';
import FoxConnectionArgs, {
foxConnectionTransformers,
} from './FoxConnectionArgs';
export const FoxConnection = createConnectionType(Fox);
@Resolver(() => Fox)
class FoxResolver {
@TransformArgs(foxConnectionTransformers)
@Query(() => FoxConnection)
async foxes(@Args() args: FoxConnectionArgs): Promise<Connection<Fox>> {
// The implementation
}
}
export default FoxResolver;
You can create your own transformers like this:
import { Transformer } from '../utils/TransformArgs';
const trim: Transformer<string> = (value) => value.trim();
export default trim;
The transformer can only be synchronous.