How to use the type-graphql.Mutation function in type-graphql

To help you get started, we’ve selected a few type-graphql examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github goldcaddy77 / warthog / examples / 07-feature-flags / src / feature-flag / feature-flag.resolver.ts View on Github external
async createFeatureFlag(
    @Arg('data') data: FeatureFlagCreateInput,
    @UserId() userId: string
  ): Promise {
    return this.service.create(data, userId);
  }

  @Mutation(() => FeatureFlag)
  async updateFeatureFlag(
    @Args() { data, where }: FeatureFlagUpdateArgs,
    @UserId() userId: string
  ): Promise {
    return this.service.update(data, where, userId);
  }

  @Mutation(() => StandardDeleteResponse)
  async deleteFeatureFlag(
    @Arg('where') where: FeatureFlagWhereUniqueInput,
    @UserId() userId: string
  ): Promise {
    // TODO: deletes across all environments.  Just takes project key and flag key
    return this.service.delete(where, userId);
  }
}
github goldcaddy77 / warthog-starter / src / modules / post / post.resolver.ts View on Github external
}

  @Mutation(() => Post)
  async createPost(@Arg('data') data: PostCreateInput, @UserId() userId: string): Promise {
    return this.service.create(data, userId);
  }

  @Mutation(() => Post)
  async updatePost(
    @Args() { data, where }: PostUpdateArgs,
    @UserId() userId: string
  ): Promise {
    return this.service.update(data, where, userId);
  }

  @Mutation(() => [Post])
  async createManyPosts(
    @Args() { data }: PostCreateManyArgs,
    @UserId() userId: string
  ): Promise {
    return this.service.createMany(data, userId);
  }

  // @Mutation(() => StandardDeleteResponse)
  // async deletePost(
  //   @Arg('where') where: PostWhereUniqueInput,
  //   @UserId() userId: string
  // ): Promise {
  //   return this.service.delete(where, userId);
  // }
}
github MichalLytek / type-graphql / experiments / prisma / generated / type-graphql / index.ts View on Github external
nullable: false,
    description: undefined
  })
  async createOneUser(@Ctx() ctx: any, @Args() args: CreateOneUserArgs): Promise {
    return ctx.photon.users.create(args);
  }

  @Mutation(_returns => User, {
    nullable: true,
    description: undefined
  })
  async deleteOneUser(@Ctx() ctx: any, @Args() args: DeleteOneUserArgs): Promise {
    return ctx.photon.users.delete(args);
  }

  @Mutation(_returns => User, {
    nullable: true,
    description: undefined
  })
  async updateOneUser(@Ctx() ctx: any, @Args() args: UpdateOneUserArgs): Promise {
    return ctx.photon.users.update(args);
  }

  @Mutation(_returns => BatchPayload, {
    nullable: false,
    description: undefined
  })
  async updateManyUser(@Ctx() ctx: any, @Args() args: UpdateManyUserArgs): Promise {
    return ctx.photon.users.updateMany(args);
  }

  @Mutation(_returns => User, {
github mgm-interns / team-radio / server / src / resolvers / song / HistorySongsCRUDResolver.ts View on Github external
id,
      songId,
      title,
      url,
      creatorId,
      stationId,
      duration,
      thumbnail,
      isPlayed,
      upVotes,
      downVotes
    );
  }

  @Authorized([UserRole.STATION_OWNER])
  @Mutation(returns => HistorySong, {
    name: 'deleteHistorySong',
    description: "Delete a song that's currently in history."
  })
  public async delete(@Arg('id') id: string): Promise {
    return this.historySongCRUDService.delete(id);
  }

  protected getDefaultFilter() {
    return {
      isPlayed: true
    };
  }
}
github birkir / prime / packages / prime-core / src / modules / internal / resolvers / AccessTokenResolver.ts View on Github external
const hashid = new Hashids(salt, 108, alphabet);
    hash.update(`${Math.floor(1000 * Math.random())}|${Date.now()}`);
    const accessToken = this.accessTokenRepository.create(input);
    const tokenSeed = hash.digest('hex').match(/.{1,8}/g) || [];
    const token = hashid.encode(tokenSeed.map(num => parseInt(num, 16)));
    if (!tokenSeed.length || token === '') {
      throw new Error('Failed to generate access token');
    }
    accessToken.token = token;
    accessToken.userId = context.user.id;
    await this.accessTokenRepository.save(accessToken);
    return accessToken;
  }

  @Authorized()
  @Mutation(returns => Boolean, { description: 'Remove Access Token by ID' })
  public async removeAccessToken(
    @Arg('id', type => ID) id: string,
    @Ctx() context: Context
  ): Promise {
    const accessToken = await this.accessTokenRepository.findOneOrFail(id);
    return Boolean(await this.accessTokenRepository.remove(accessToken));
  }
}
github goldcaddy77 / warthog / examples / 04-many-to-many-relationship / src / join-with-metadata / role.resolver.ts View on Github external
import { BaseContext, BaseResolver } from '../../../../src';
import { RoleCreateInput, RoleWhereArgs, RoleWhereInput } from '../../generated';
import { Role } from './role.model';

@Resolver(Role)
export class RoleResolver extends BaseResolver {
  constructor(@InjectRepository(Role) public readonly roleRepository: Repository) {
    super(Role, roleRepository);
  }

  @Query(() => [Role])
  async roles(@Args() { where, orderBy, limit, offset }: RoleWhereArgs): Promise {
    return this.find(where, orderBy, limit, offset);
  }

  @Mutation(() => Role)
  async createRole(@Arg('data') data: RoleCreateInput, @Ctx() ctx: BaseContext): Promise {
    return this.create(data, ctx.user.id);
  }
}
github benawad / codeponder / packages / server / src / modules / code-review-post / resolver.ts View on Github external
import { isAuthenticated } from "../shared/middleware/isAuthenticated";
import { CreateCodeReviewPostInput } from "./createInput";
import { FindCodeReviewPostInput } from "./findInput";
import { FindCodeReviewPostResponse } from "./findResponse";
import { CodeReviewPostResponse } from "./response";

@Resolver(CodeReviewPost)
export class CodeReviewPostResolvers {
  constructor(
    @InjectRepository(CodeReviewQuestionRepository)
    private readonly questionRepo: CodeReviewQuestionRepository,
    @InjectRepository(CodeReviewPostRepository)
    private readonly postRepo: CodeReviewPostRepository
  ) {}

  @Mutation(() => CodeReviewPostResponse)
  @UseMiddleware(isAuthenticated)
  async findOrCreateCodeReviewPost(
    @Arg("codeReviewPost") input: CreateCodeReviewPostInput,
    @Ctx() { req }: MyContext
  ): Promise {
    let value = await this.postRepo.findOne({
      where: {
        commitId: input.commitId,
        repo: input.repo,
        repoOwner: input.repoOwner,
      },
    });

    if (!value) {
      value = await this.postRepo.save({
        ...input,
github kevenleone / graphscript / src / utils / createBaseResolver.ts View on Github external
@UseMiddleware(isAuth)
    @Query(() => [returnType], { name: `getAll${suffix}Paginate` })
    async getAllPagination(@Arg('data', () => PaginationQL) data: PaginationQL): Promise {
      const { skip, take } = normalizePagination(data);
      return entity.find({ skip, take });
    }

    @UseMiddleware(isAuth)
    @Query(() => returnType, { name: `get${suffix}` })
    async get(@Arg('id', () => String) id: string): Promise {
      return entity.findOne(id);
    }

    @UseMiddleware(isAuth)
    @Mutation(() => returnType, { name: `create${suffix}` })
    async create(@Arg('data', () => inputTypes.create) data: any): Promise {
      if (middlewares && middlewares.create.before) {
        middlewares.create.before(data);
      }
      return entity.create(data).save();
    }

    @UseMiddleware(isAuth)
    @Mutation(() => returnType, { name: `updateBy${suffix}ID` })
    async updateByID(@Arg('data', () => inputTypes.update) data: any, @Arg('id') id: string): Promise {
      const entityData = await this.get(id);
      return this.update(data, entityData);
    }

    @UseMiddleware(isAuth)
    @Mutation(() => [returnType], { name: `createMulti${suffix}` })
github birkir / prime / packages / prime-core / src / modules / internal / resolvers / DocumentResolver.ts View on Github external
qb.having(`Document.id = ${subquery.getQuery()}`);
        qb.groupBy('Document.id');
        return qb;
      },
      repository: this.documentRepository,
      sortOptions: sortOptions(sorts),
    });

    (result as any).totalCount = 15;

    return result;
  }

  @Authorized()
  @Mutation(returns => Document)
  public async createDocument(
    @Arg('input', type => DocumentInput) input: DocumentInput,
    @Ctx() context: Context
  ): Promise {
    const schema = await this.schemaRepository.findOneOrFail(input.schemaId, { cache: 1000 });
    const document = await this.documentRepository.insert({
      ...input,
      data: await this.documentTransformer.transformInput(input.data, schema),
      userId: context.user.id,
      documentId:
        input.documentId || (await getUniqueHashId(this.documentRepository, 'documentId')),
    });
    const doc = document.identifiers.pop() || { id: null };
    return this.documentRepository.findOneOrFail(doc.id);
  }
github forsigner / egg-type-graphql / example / app / recipe / resolver / sample.resolver.ts View on Github external
@Query(() => Date)
  currentDate() {
    return new Date();
  }

  @Mutation(() => Boolean)
  async pubSubMutation(
    @PubSub() pubSub: PubSubEngine,
    @Arg('message', { nullable: true }) message?: string,
  ): Promise {
    const payload: NotificationPayload = { id: ++this.autoIncrement, message };
    await pubSub.publish('NOTIFICATIONS', payload);
    return true;
  }

  @Mutation(() => Boolean)
  async publisherMutation(
    @PubSub('NOTIFICATIONS') publish: Publisher,
    @Arg('message', { nullable: true }) message?: string,
  ): Promise {
    await publish({ id: ++this.autoIncrement, message });
    return true;
  }

  @Subscription({ topics: 'NOTIFICATIONS' })
  normalSubscription(@Root()
  {
    id,
    message,
  }: NotificationPayload): Notification {
    return { id, message, date: new Date() };
  }