type-graphql#Args TypeScript Examples

The following examples show how to use type-graphql#Args. 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: topic.resolver.ts    From hakka with MIT License 6 votes vote down vote up
@Mutation((returns) => Boolean)
  async likeTopic(@GqlContext() ctx: Context, @Args() args: LikeTopicArgs) {
    const user = requireAuth(ctx)
    const topic = await prisma.topic.findUnique({
      where: {
        id: args.topicId,
      },
    })
    if (!topic) throw new ApolloError(`topic was not found`)
    let userTopicLike = await prisma.userTopicLike.findFirst({
      where: {
        topicId: topic.id,
        userId: user.id,
      },
    })
    let liked = false
    if (userTopicLike) {
      await prisma.userTopicLike.delete({
        where: {
          id: userTopicLike.id,
        },
      })
    } else {
      userTopicLike = await prisma.userTopicLike.create({
        data: {
          topicId: topic.id,
          userId: user.id,
        },
      })
      liked = true
    }
    return liked
  }
Example #2
Source File: Lua.resolver.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
@Query(() => LuaScript)
  async luaScript(
    @Args() args: LuaArgs,
    @Arg('gitRepository') gitRepository: GitRepository
  ): Promise<LuaScript> {
    const fileLocation = await this.luaService.loadLuaScript(
      args,
      gitRepository
    );
    return { fileLocation };
  }
Example #3
Source File: topic.resolver.ts    From hakka with MIT License 6 votes vote down vote up
@Mutation((returns) => Topic)
  async updateTopic(@GqlContext() ctx: Context, @Args() args: UpdateTopicArgs) {
    const user = requireAuth(ctx)
    const topic = await prisma.topic.findUnique({
      where: {
        id: args.id,
      },
    })
    if (!topic) {
      throw new ApolloError(`主题不存在`)
    }

    // Allow the author and admins to update the topic
    if (topic.authorId !== user.id && !isAdmin(user)) {
      throw new ApolloError(`没有访问权限`)
    }

    const result = await prisma.topic.update({
      where: {
        id: topic.id,
      },
      data: {
        title: args.title,
        content: args.content,
      },
    })

    return result
  }
Example #4
Source File: message-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @Query(() => Messages)
  async getMessages(@Args() { after, before, limit, roomId }: getMessagesArgs) {
    const afterQuery = after && { $gt: new ObjectID(b64decode(after)) };
    const beforeQuery = before && { $lt: new ObjectID(b64decode(before)) };
    const criteria =
      afterQuery || beforeQuery
        ? {
            _id: { ...afterQuery, ...beforeQuery },
          }
        : {};

    let messages = await MessageModel.find({ roomId: roomId, ...criteria })
      .limit(limit + 1)
      .sort({ createdAt: afterQuery ? 0 : -1 })
      .populate("author")
      .lean();

    const hasNext = messages.length > limit - 1;
    if (hasNext) {
      messages = messages.slice(0, messages.length - 1);
    }
    const edges = messages.map(edge => ({
      cursor: b64encode(edge._id.toHexString()),
      node: edge,
    }));

    return {
      pageInfo: {
        hasNext: hasNext,
      },
      edges: edges.reverse(),
    };
  }
Example #5
Source File: topic.resolver.ts    From hakka with MIT License 6 votes vote down vote up
@Mutation((returns) => Topic)
  async createTopic(@GqlContext() ctx: Context, @Args() args: CreateTopicArgs) {
    const user = requireAuth(ctx)

    const topic = await prisma.topic.create({
      data: {
        authorId: user.id,
        title: args.title,
        content: args.content,
        url: args.url,
      },
    })

    return topic
  }
Example #6
Source File: message-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit({ limit: 2000 }))
  @Mutation(() => Message)
  async editMessage(
    @Args() { messageId, content }: editMessageArgs,
    @Ctx() context: Context,
    @PubSub() pubsub: PubSubEngine
  ) {
    try {
      const message = await MessageModel.findOneAndUpdate(
        {
          _id: messageId,
          author: context.currentUser.id,
        },
        { content: content },
        { new: true }
      );
      if (!message) throw new ApolloError("Cannot find message with ID");

      await message.populate("author").execPopulate();
      pubsub.publish(CONSTANTS.UPDATE_MESSAGE, message.toObject());

      return message;
    } catch (err) {
      throw new ApolloError(err);
    }
  }
Example #7
Source File: room-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit({ limit: 20 }))
  @Mutation(() => Room)
  async createRoom(@Args() { name }: createRoomArgs, @Ctx() context: Context) {
    try {
      const room = new RoomModel({
        name: name,
        messages: [],
        members: [context.currentUser.id],
        owner: context.currentUser.id,
      });
      await room.populate("members").execPopulate();

      await UserModel.findByIdAndUpdate(
        context.currentUser.id,
        { $addToSet: { rooms: room._id } },
        { new: true }
      );
      const savedRoom = await room.save();

      return savedRoom;
    } catch (err) {
      throw new ApolloError(err);
    }
  }
Example #8
Source File: room-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit())
  @Mutation(() => Member, { nullable: true })
  async removeMemberFromRoom(
    @Args() { roomId, memberId }: removeMembersArgs,
    @Ctx() context: Context
  ): Promise<Member> {
    try {
      if (memberId.equals(context.currentUser.id)) {
        throw new ApolloError("You cannot not remove yourself from room");
      }

      const room = await RoomModel.findOneAndUpdate(
        {
          _id: roomId,
          owner: context.currentUser.id,
        },
        { $pull: { members: memberId } },
        { new: true }
      );

      const removedMember = await UserModel.findOneAndUpdate(
        { _id: memberId },
        { $pull: { rooms: roomId } },
        { new: true }
      );

      if (!removedMember || !room) {
        throw new ApolloError("Could not remove member from room");
      }

      return removedMember;
    } catch (err) {
      throw new ApolloError(err);
    }
  }
Example #9
Source File: user-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit({ limit: 500 }))
  @Mutation(returns => Member)
  async setColor(@Args() { color }: setColorArgs, @Ctx() context: Context) {
    try {
      const user = await UserModel.findOneAndUpdate(
        { _id: context.currentUser.id },
        { color: color },
        { new: true }
      );
      if (!user) throw new ApolloError("User not found with id");
      return user;
    } catch (err) {
      throw new ApolloError(err);
    }
  }
Example #10
Source File: user-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit({ limit: 500 }))
  @Mutation(returns => Member)
  async setUserLinks(@Args() links: setUserLinksArgs, @Ctx() context: Context) {
    try {
      const foundUser = await UserModel.findOne({
        _id: context.currentUser.id,
      });
      if (!foundUser) throw new ApolloError("User not found with id");

      const linksToBeUpdated = { ...foundUser.toObject().links, ...links };

      const user = await UserModel.findOneAndUpdate(
        { _id: context.currentUser.id },
        {
          $set: { links: linksToBeUpdated },
        },
        { new: true }
      );
      return user;
    } catch (err) {
      throw new ApolloError(err);
    }
  }
Example #11
Source File: comment.resolver.ts    From hakka with MIT License 6 votes vote down vote up
@Query((returns) => CommentsConnection)
  async comments(@Args() args: CommentsArgs) {
    const skip = (args.page - 1) * args.take

    const comments = await prisma.comment.findMany({
      where: {
        topicId: args.topicId,
      },
      take: args.take + 1,
      skip,
      orderBy: {
        createdAt: args.order,
      },
    })
    const count = await prisma.comment.count({
      where: {
        topicId: args.topicId,
      },
    })

    return {
      items: comments.slice(0, args.take),
      hasNext: comments.length > args.take,
      hasPrev: args.page > 1,
      total: count,
    }
  }
Example #12
Source File: topic.resolver.ts    From hakka with MIT License 6 votes vote down vote up
@Query((returns) => Topic)
  async topicById(@Args() args: TopicByIdArgs) {
    const topic = await prisma.topic.findUnique({
      where: {
        id: args.id,
      },
    })
    return topic
  }
Example #13
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 #14
Source File: topic.resolver.ts    From hakka with MIT License 6 votes vote down vote up
@Query((returns) => TopicsConnection)
  async topics(@GqlContext() ctx: Context, @Args() args: TopicsArgs) {
    const skip = (args.page - 1) * args.take

    const topics: TODO = await prisma.$queryRaw`
    select "topic".* from "topics" "topic"
      left join "comments" "lastComment"
        on "lastComment"."id" = "topic"."lastCommentId"
        where "topic"."hidden" is not true
    order by
      case when "lastComment" is null then "topic"."createdAt" else "lastComment"."createdAt" end DESC
    limit ${args.take}
    offset ${skip};
    `
    return {
      items: topics.slice(0, args.take).map((topic: any) => ({
        ...topic,
        createdAt: new Date(topic.createdAt),
        updatedAt: new Date(topic.updatedAt),
      })),
      hasNext: topics.length > args.take,
      hasPrev: args.page !== 1,
    }
  }
Example #15
Source File: student.ts    From Koa-GraphQL-Template with MIT License 5 votes vote down vote up
@Query(() => [Student], { nullable: true, description: '查询学生列表' })
    async students(@Args() args: StudentArgs) {
        // TODO args have to be required?
        return await StudentModel.find(args);
    }
Example #16
Source File: user.resolver.ts    From hakka with MIT License 5 votes vote down vote up
@Query((returns) => Profile)
  async profile(@Args() args: ProfileArgs) {
    const user = await prisma.user.findUnique({
      where: { username: args.username },
    })
    return user
  }
Example #17
Source File: comment.resolver.ts    From hakka with MIT License 5 votes vote down vote up
@Mutation((returns) => Comment)
  async createComment(
    @GqlContext() ctx: Context,
    @Args() args: CreateCommentArgs,
  ) {
    const user = requireAuth(ctx)
    const comment = await prisma.comment.create({
      data: {
        topic: {
          connect: {
            id: args.topicId,
          },
        },
        content: args.content,
        author: {
          connect: {
            id: user.id,
          },
        },
        parent: args.parentId
          ? {
              connect: {
                id: args.parentId,
              },
            }
          : undefined,
      },
    })

    await prisma.topic.update({
      where: {
        id: args.topicId,
      },
      data: {
        lastComment: {
          connect: {
            id: comment.id,
          },
        },
      },
    })

    // Add notification
    notificationQueue.add({ commentId: comment.id })

    return comment
  }
Example #18
Source File: message-resolver.ts    From convoychat with GNU General Public License v3.0 5 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit({ limit: 1000 }))
  @Mutation(() => Message)
  async sendMessage(
    @Args() { roomId, content }: sendMessageArgs,
    @Ctx() context: Context,
    @PubSub() pubsub: PubSubEngine
  ) {
    try {
      const room = await RoomModel.findOne({
        _id: roomId,
        members: { $in: [context.currentUser.id] },
      }).populate("members");

      if (!room) {
        throw new ApolloError(
          "Room not found or you are not a member of this room"
        );
      }

      // parse mentions
      const mentions = parseMentions(content);

      // check if mentioned users are member of the room
      const mentioned_users = mentions
        .map(m => {
          const found = room?.members.find((i: Member) => i.username === m);
          if (found) {
            return (found as any)._id;
          }
          return null;
        })
        // remove null values & current user if mentioned
        .filter(userId => {
          if (!userId) return false;
          return `${userId}` !== `${context.currentUser.id}`;
        });

      const message = new MessageModel({
        content: content,
        roomId: roomId,
        author: context.currentUser.id,
        mentions: mentioned_users,
      });
      message.populate("author").execPopulate();

      // filter out the current User id to prevent self notification sending
      const mentionNotifications = message.mentions.map(async id => {
        return sendNotification({
          context: context,
          sender: context.currentUser.id,
          receiver: id as any,
          type: NOTIFICATION_TYPE.MENTION,
          payload: {
            roomName: room?.name,
            message: message.content,
            messageId: message._id,
            roomId: room?._id,
          },
        });
      });

      await Promise.all(mentionNotifications);

      (message as any).$roomId = roomId;
      const savedMessage = await message.save();
      pubsub.publish(CONSTANTS.NEW_MESSAGE, savedMessage.toObject());

      return savedMessage;
    } catch (err) {
      throw new ApolloError(err);
    }
  }
Example #19
Source File: invitation-resolver.ts    From convoychat with GNU General Public License v3.0 5 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit({ limit: 15 }))
  @Mutation(() => [Invitation])
  async inviteMembers(
    @Args() { roomId, members }: inviteMembersArgs,
    @Ctx() context: Context
  ) {
    try {
      // check if user is a memeber of the specified room
      const user = await UserModel.findOne({
        _id: context.currentUser.id,
        rooms: { $in: [roomId] },
      });

      if (!user) {
        throw new ApolloError(
          "You are not a member of room, Cannot invite members"
        );
      }

      let token = null;

      // create invitations
      const invitations = members.map(memberId => {
        token = crypto.randomBytes(16).toString("hex");
        const invite = new InvitationModel({
          roomId: roomId,
          userId: memberId,
          invitedBy: context.currentUser.id,
          token: token,
        });

        return invite.save();
      });

      // @ts-ignore
      const savedInvites: Invitation[] = await Promise.all(invitations);

      const foundRoom = await RoomModel.findOne({ _id: roomId });

      // send notification
      const notifications = members.map(async (id, index) => {
        return sendNotification({
          context: context,
          sender: context.currentUser.id,
          receiver: id,
          type: NOTIFICATION_TYPE.INVITATION,
          payload: {
            userId: id,
            roomName: foundRoom.name,
            roomId: roomId,
            invitedBy: context.currentUser.id,
            token: savedInvites[index].token,
          },
        });
      });

      await Promise.all(notifications);

      // TODO: Send Email invitations

      return savedInvites;
    } catch (err) {
      console.log(err);
      throw new ApolloError(err);
    }
  }
Example #20
Source File: Firmware.resolver.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 5 votes vote down vote up
@Query(() => [UserDefine])
  async targetDeviceOptions(
    @Args() args: TargetDeviceOptionsArgs,
    @Arg('gitRepository') gitRepository: GitRepository
  ): Promise<UserDefine[]> {
    return this.userDefinesBuilder.build(args, gitRepository);
  }
Example #21
Source File: Firmware.resolver.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 5 votes vote down vote up
@Query(() => [Device])
  async availableFirmwareTargets(
    @Args() args: TargetArgs,
    @Arg('gitRepository') gitRepository: GitRepository
  ): Promise<Device[]> {
    return this.targetsLoaderService.loadTargetsList(args, gitRepository);
  }
Example #22
Source File: create-generic-entity.ts    From Cromwell with MIT License 4 votes vote down vote up
createGenericEntity = <EntityType, EntityInputType = EntityType>(entityName: string,
    EntityClass: new (...args: any[]) => EntityType,
    InputEntityClass?: new (...args: any[]) => EntityInputType) => {

    @EntityRepository(EntityClass)
    class GenericRepository extends BaseRepository<EntityType, EntityInputType> {
        constructor() {
            super(EntityClass)
        }
    }

    @ObjectType(`Paged${entityName}`)
    class PagedEntity implements TPagedList<EntityType> {
        @Field(() => PagedMeta, { nullable: true })
        pagedMeta?: PagedMeta;

        @Field(() => [EntityClass], { nullable: true })
        elements?: EntityType[];
    }

    @ArgsType()
    class CreateArgs {
        @Field(() => InputEntityClass ?? String)
        data: EntityInputType;
    }

    @ArgsType()
    class UpdateArgs {
        @Field(() => Int)
        id: number;

        @Field(() => InputEntityClass ?? String)
        data: EntityInputType;
    }

    const getPagedPath = GraphQLPaths.Generic.getManyPaged + entityName;
    const getAllPath = GraphQLPaths.Generic.getMany + entityName;
    const getBySlugPath = GraphQLPaths.Generic.getOneBySlug + entityName;
    const getByIdPath = GraphQLPaths.Generic.getOneById + entityName;
    const createPath = GraphQLPaths.Generic.create + entityName;
    const updatePath = GraphQLPaths.Generic.update + entityName;
    const deletePath = GraphQLPaths.Generic.delete + entityName;
    const getFilteredPath = GraphQLPaths.Generic.getFiltered + entityName;

    @Resolver(EntityClass, { isAbstract: true })
    abstract class GenericResolver {

        private repository = getCustomRepository(GenericRepository)

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => PagedEntity)
        async [getPagedPath](@Arg("pagedParams") pagedParams: PagedParamsInput<EntityType>):
            Promise<TPagedList<EntityType>> {
            return this.repository.getPaged(pagedParams);
        }

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => [EntityClass])
        async [getAllPath](): Promise<EntityType[]> {
            return this.repository.getAll();
        }

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => EntityClass)
        async [getBySlugPath](@Arg("slug") slug: string): Promise<EntityType | undefined> {
            return this.repository.getBySlug(slug);
        }

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => EntityClass)
        async [getByIdPath](@Arg("id", () => Int) id: number): Promise<EntityType | undefined> {
            return this.repository.getById(id);
        }

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => PagedEntity)
        async [getFilteredPath](
            @Arg("pagedParams", () => PagedParamsInput, { nullable: true }) pagedParams?: PagedParamsInput<EntityType>,
            @Arg("filterParams", () => BaseFilterInput, { nullable: true }) filterParams?: BaseFilterInput,
        ): Promise<TPagedList<EntityType> | undefined> {
            return this.repository.getFilteredEntities(pagedParams, filterParams);
        }

        @Authorized<TAuthRole>("administrator")
        @Mutation(() => EntityClass)
        async [createPath](@Args() { data }: CreateArgs): Promise<EntityType> {
            return this.repository.createEntity(data);
        }

        @Authorized<TAuthRole>("administrator")
        @Mutation(() => EntityClass)
        async [updatePath](@Args() { id, data }: UpdateArgs): Promise<EntityType> {
            return this.repository.updateEntity(id, data);
        }

        @Authorized<TAuthRole>("administrator")
        @Mutation(() => Boolean)
        async [deletePath](@Arg("id", () => Int) id: number): Promise<boolean> {
            return this.repository.deleteEntity(id);
        }

    }

    return {
        abstractResolver: GenericResolver as any,
        repository: GenericRepository as TObjectType<BaseRepository<EntityType, EntityInputType>>,
        pagedEntity: PagedEntity as any,
        createArgs: CreateArgs as any,
        updateArgs: UpdateArgs as any,
    }
}