type-graphql#Mutation TypeScript Examples

The following examples show how to use type-graphql#Mutation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: coupon.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
@Authorized<TAuthRole>("administrator")
    @Mutation(() => Boolean)
    async [deleteManyFilteredPath](
        @Arg("input") input: DeleteManyInput,
        @Arg("filterParams", () => BaseFilterInput, { nullable: true }) filterParams?: BaseFilterInput,
    ): Promise<boolean | undefined> {
        const res = await this.repository.deleteManyFilteredCoupons(input, filterParams);
        resetAllPagesCache();
        return res;
    }
Example #2
Source File: Firmware.resolver.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
@Mutation(() => BuildFlashFirmwareResult)
  async buildFlashFirmware(
    @Arg('input') input: BuildFlashFirmwareInput,
    @Arg('gitRepository') gitRepository: GitRepository
  ): Promise<BuildFlashFirmwareResult> {
    return this.firmwareService.buildFlashFirmware(
      input,
      gitRepository.url,
      gitRepository.srcFolder
    );
  }
Example #3
Source File: invitation-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @Mutation(() => InvitationLinkResult)
  async createInvitationLink(
    @Arg("roomId", { nullable: false }) roomId: ObjectID,
    @Ctx() context: Context
  ) {
    const existingInvitation = await InvitationModel.findOne({
      roomId: roomId,
      invitedBy: context.currentUser.id,
      isPublic: true,
    });

    const baseURL =
      process.env.NODE_ENV !== "production"
        ? "http://localhost:3000"
        : "https://convoychat.herokuapp.com";

    if (existingInvitation) {
      return {
        link: `${baseURL}/invitation/${existingInvitation.token}`,
      };
    }

    const validRoom = await RoomModel.findOne({ _id: roomId });
    if (!validRoom) throw new Error("Not a valid room");

    // TODO: add expiry time in invitation token
    const token = crypto.randomBytes(16).toString("hex");
    const invite = new InvitationModel({
      isPublic: true,
      roomId: roomId,
      invitedBy: context.currentUser.id,
      token: token,
    });

    await invite.save();

    return { link: `${baseURL}/invitation/${token}` };
  }
Example #4
Source File: DepartmentService.ts    From graphql-ts-client with MIT License 6 votes vote down vote up
@Mutation(() => Department)
    async mergeDepartment(
        @Arg("input", () => DepartmentInput) input: DepartmentInput
    ): Promise<Department> {
        /*
         * Mock the network delay
         */
        await delay(1000);

        departmentTable.insert(input, true);
        return new Department(input);
    }
Example #5
Source File: post.ts    From lireddit with MIT License 6 votes vote down vote up
@Mutation(() => Post)
  @UseMiddleware(isAuth)
  async createPost(
    @Arg("input") input: PostInput,
    @Ctx() { req }: MyContext
  ): Promise<Post> {
    return Post.create({
      ...input,
      creatorId: req.session.userId,
    }).save();
  }
Example #6
Source File: ChatRoom.resolver.ts    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
@Mutation(() => Boolean)
  async createChatRoom(@Arg('data') data: ChatRoomCreateInput) {
    const queryBuilder = await getConnection()
      .createQueryBuilder()
      .insert()
      .into(ChatRoomEntity)
      .values([data])
      .execute();

    console.log(queryBuilder);

    return true;
  }
Example #7
Source File: UserAccount.ts    From Wern-Fullstack-Template with MIT License 6 votes vote down vote up
@Mutation(() => UserResponse)
  async createUser(@Arg('options') options: UserInput): Promise<UserResponse> {
    const errors = validateRegister(options)
    if (errors) {
      return { errors }
    }

    const hashedPassword = await argon2.hash(options.password)
    let user
    try {
      const result = await getConnection()
        .createQueryBuilder()
        .insert()
        .into(UserAccount)
        .values({
          username: options.username,
          email: options.email,
          password: hashedPassword,
        })
        .returning('*')
        .execute()
      user = result.raw[0]
    } catch (err) {
      if (err.code === '23505') {
        return {
          errors: [
            {
              field: 'username',
              message: 'username already taken',
            },
          ],
        }
      }
    }

    return { user }
  }
Example #8
Source File: authentication.ts    From backend with MIT License 6 votes vote down vote up
@Authorized(Role.UNAUTHENTICATED)
    @Mutation(returns => Boolean)
    @Deprecated("Use loginPassword instead")
    async loginPasswordLegacy(@Ctx() context: GraphQLContext, @Arg("email") email: string, @Arg("password") password: string) {
        ensureSession(context);
        const logger = logInContext(`GraphQL Authentication`, context);

        const screener = await prisma.screener.findFirst({
            where: {
                email,
                active: true
            }
        });

        const passwordValid = screener && await verifyPassword(password, screener.password);

        if (!screener || !passwordValid) {
            logger.warn(`Invalid email (${email}) or password`);
            throw new AuthenticationError("Invalid email or password");
        }

        await loginAsUser(userForScreener(screener), context);

        return true;
    }
Example #9
Source File: author.resolver.ts    From mikro-orm-graphql-example with MIT License 6 votes vote down vote up
@Mutation(() => Author)
  public async updateAuthor(
    @Arg('input') input: AuthorValidator,
    @Arg('id') id: string,
    @Ctx() ctx: MyContext,
    @Info() info: GraphQLResolveInfo,
  ): Promise<Author> {
    const relationPaths = fieldsToRelations(info);
    const author = await ctx.em.getRepository(Author).findOneOrFail({ id }, relationPaths);
    author.assign(input);
    await ctx.em.persist(author).flush();
    return author;
  }
Example #10
Source File: comment.resolver.ts    From hakka with MIT License 6 votes vote down vote up
@Mutation((returns) => Boolean)
  async likeComment(@GqlContext() ctx: Context, @Args() args: LikeCommentArgs) {
    const user = requireAuth(ctx)
    const comment = await prisma.comment.findUnique({
      where: {
        id: args.commentId,
      },
    })
    if (!comment) throw new ApolloError(`comment was not found`)
    let userCommentLike = await prisma.userCommentLike.findFirst({
      where: {
        commentId: comment.id,
        userId: user.id,
      },
    })
    let liked = false
    if (userCommentLike) {
      await prisma.userCommentLike.delete({
        where: {
          id: userCommentLike.id,
        },
      })
    } else {
      userCommentLike = await prisma.userCommentLike.create({
        data: {
          commentId: comment.id,
          userId: user.id,
        },
      })
      liked = true
    }
    return liked
  }
Example #11
Source File: grow.map.resolver.ts    From liferay-grow with MIT License 6 votes vote down vote up
@Mutation(() => Boolean, { name: 'updateGrowMapOfficeDetails' })
  @Authorized()
  async updateGrowMapOfficeDetails(
    @Arg('data') data: UserDetailBaseInput,
    @Ctx() ctx: MyContext,
  ): Promise<boolean> {
    const user = await getUserFromCtxOrFail(ctx, [
      ...relations,
      'growMap.userDetails',
    ]);

    if (!user.growMap) {
      throw new Error('Grow Map not exists');
    }

    await saveUserDetails(data, user.growMap.userDetails);

    return true;
  }