type-graphql#Arg TypeScript Examples

The following examples show how to use type-graphql#Arg. 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: mutation.ts    From backend with MIT License 6 votes vote down vote up
@Mutation(returns => Boolean)
    @Authorized(Role.PUPIL, Role.ADMIN)
    async meBecomeStatePupil(@Ctx() context: GraphQLContext, @Arg("data") data: BecomeStatePupilInput, @Arg("pupilId", { nullable: true}) pupilId: number) {
        const pupil = await getSessionPupil(context, pupilId);
        const log = logInContext("Me", context);

        const updatedPupil = await becomeStatePupil(pupil, data);
        await evaluatePupilRoles(updatedPupil, context);

        log.info(`Pupil(${pupil.id}) upgraded their account to become a STATE_PUPIL`);

        return true;
    }
Example #2
Source File: invitation-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @Query(() => InvitationDetails)
  async getInvitationInfo(
    @Arg("token", { nullable: false }) token: string,
    @Ctx() context: Context
  ) {
    const invite = await InvitationModel.findOne({
      token: token,
    })
      .populate("roomId")
      .populate("invitedBy");

    if (!invite) {
      throw new ApolloError("Could not get invitation info");
    }

    const userid = new ObjectID(context.currentUser.id);
    const currentUserInvite = userid.equals(invite.userId as ObjectId);
    if (!currentUserInvite && !invite.isPublic) {
      throw new ApolloError("Could not get invitation info");
    }

    return {
      id: invite.id,
      room: invite.roomId,
      invitedBy: invite.invitedBy,
      isPublic: invite.isPublic,
      createdAt: invite.createdAt,
    };
  }
Example #3
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 #4
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 #5
Source File: SerialMonitor.resolver.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
@Mutation(() => SerialPortConnectResult)
  async connectToSerialDevice(
    @Arg('input') input: SerialConnectionConfigInput
  ): Promise<SerialPortConnectResult> {
    try {
      await this.serialMonitorService.connect(input.port, input.baudRate);
      return new SerialPortConnectResult(true);
    } catch (e) {
      return new SerialPortConnectResult(false, `Error occurred: ${e}`);
    }
  }
Example #6
Source File: mutations.ts    From backend with MIT License 6 votes vote down vote up
@Mutation(returns => Boolean)
    @AuthorizedDeferred(Role.ADMIN, Role.OWNER)
    async matchDissolve(@Ctx() context: GraphQLContext, @Arg("matchId") matchId: number, @Arg("dissolveReason") dissolveReason: number): Promise<boolean> {
        const match = await getMatch(matchId);
        await hasAccess(context, "Match", match);

        await dissolveMatch(match, dissolveReason, /* dissolver:*/ null);

        return true;
    }
Example #7
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 #8
Source File: mutations.ts    From backend with MIT License 6 votes vote down vote up
@Mutation((returns) => Boolean)
    @AuthorizedDeferred(Role.ADMIN, Role.OWNER)
    async courseSubmit(@Ctx() context: GraphQLContext, @Arg("courseId") courseId: number): Promise<boolean> {
        const course = await getCourse(courseId);
        await hasAccess(context, "Course", course);
        await prisma.course.update({ data: { courseState: "submitted"}, where: { id: courseId}});
        logger.info(`Course (${courseId}) submitted by Student (${context.user.studentId})`);
        return true;
    }
Example #9
Source File: custom-entity.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", { nullable: true }) filterParams?: CustomEntityFilterInput,
    ): Promise<boolean | undefined> {
        const res = await this.repository.deleteManyFilteredCustomEntities(input, filterParams);
        resetAllPagesCache();
        return res;
    }
Example #10
Source File: mutations.ts    From backend with MIT License 6 votes vote down vote up
@Mutation((returns) => GraphQLModel.Course)
    @Authorized(Role.ADMIN, Role.INSTRUCTOR)
    async courseCreate(@Ctx() context: GraphQLContext, @Arg("course") course: PublicCourseCreateInput, @Arg("studentId", { nullable: true }) studentId?: number): Promise<GraphQLModel.Course> {
        const student = await getSessionStudent(context, studentId);
        const result = await prisma.course.create({ data: { ...course, courseState: "created" } });
        await prisma.course_instructors_student.create({data: { courseId: result.id, studentId: student.id}});
        logger.info(`Course (${result.id}) created by Student (${student.id})`);
        return result;
    }
Example #11
Source File: order.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
@Authorized<TAuthRole>("all")
    @Query(() => PagedOrder)
    async [getOrdersOfUser](
        @Ctx() ctx: TGraphQLContext,
        @Arg("userId", () => Int) userId: number,
        @Arg("pagedParams", { nullable: true }) pagedParams?: PagedParamsInput<TOrder>
    ): Promise<TPagedList<TOrder> | undefined> {
        if (!ctx?.user?.role) throw new HttpException('Access denied.', HttpStatus.UNAUTHORIZED);

        if (!(ctx.user.role === 'guest' || ctx.user.role === 'administrator' ||
            ctx.user.id + '' === userId + '')) {
            throw new HttpException('Access denied.', HttpStatus.FORBIDDEN);
        }
        const orders = await this.repository.getOrdersOfUser(userId, pagedParams);
        return orders;
    }
Example #12
Source File: mutations.ts    From backend with MIT License 6 votes vote down vote up
@Mutation(returns => Boolean)
    @Authorized(Role.ADMIN)
    // eslint-disable-next-line camelcase
    async certificateOfConductCreate(
        @Arg("dateOfInspection") dateOfInspection: Date,
        @Arg("dateOfIssue") dateOfIssue: Date,
        @Arg("criminalRecords") criminalRecords: boolean,
        @Arg("studentId") studentId: number) {
        await CertificateOfConduct.create(dateOfInspection, dateOfIssue, criminalRecords, studentId);
        return true;
    }
Example #13
Source File: order.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
@Authorized<TAuthRole>("all")
    @Query(() => Order)
    async [getOneByIdPath](
        @Ctx() ctx: TGraphQLContext,
        @Arg("id", () => Int) id: number
    ): Promise<Order | undefined> {
        if (!ctx?.user?.role) throw new HttpException('Access denied.', HttpStatus.UNAUTHORIZED);

        const order = await this.repository.getOrderById(id);
        if (ctx.user.role === 'guest' || ctx.user.role === 'administrator' ||
            (order?.userId && ctx.user.id + '' === order.userId + ''))
            return order;
    }
Example #14
Source File: mutations.ts    From backend with MIT License 6 votes vote down vote up
@Mutation(returns => Boolean)
    @Authorized(Role.ADMIN)
    // eslint-disable-next-line camelcase
    async certificateOfConductUpdate(@Arg("studentId") studentId: number,
        @Arg("criminalRecord") criminalRecord:boolean,
        @Arg("dateOfIssue") dateOfIssue: Date,
        @Arg("dateOfInspection") dateOfInspection: Date) {
        const student = await getStudent(studentId);
        if (criminalRecord) {
            logger.info(`Updating criminal record for student ${studentId}`);
            await deactivateStudent(student);
        }
        await updateCertificateOfConduct(student, criminalRecord, dateOfIssue, dateOfInspection);
        return true;
    }
Example #15
Source File: image-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@UseMiddleware(RateLimit({ limit: 10 }))
  @Mutation(() => UploadImageOutput)
  async uploadImage(
    @Arg("file", () => GraphQLUpload) file: Promise<IUpload>
  ): Promise<UploadImageOutput> {
    const { createReadStream } = await file;
    const fileStream = createReadStream();

    return new Promise((resolve, reject) => {
      const cloudStream = cloudinary.uploader.upload_stream(
        {
          unique_filename: true,
          folder: process.env.MEDIA_FOLDER,
        },
        (err, fileUploaded) => {
          if (err) reject(false);

          resolve({
            url: fileUploaded.secure_url,
            public_id: fileUploaded.public_id,
          });
        }
      );

      fileStream.pipe(cloudStream);
    });
  }
Example #16
Source File: mutations.ts    From backend with MIT License 6 votes vote down vote up
@Mutation(returns => Boolean)
    @Authorized(Role.PUPIL)
    async participationCertificateSign(
        @Ctx() context: GraphQLContext,
        @Arg("certificateId") certificateId: string,
        @Arg("signaturePupil", { nullable: true }) signaturePupil: string | null,
        @Arg("signatureParent", { nullable: true }) signatureParent: string | null,
        @Arg("signatureLocation") signatureLocation: string): Promise<boolean> {

        const pupil = await getSessionPupil(context);

        if (!signaturePupil && !signatureParent) {
            throw new ValidationError(`Either signatureParent or signaturePupil must be present`);
        }

        await signCertificate(certificateId, pupil, signatureParent, signaturePupil, signatureLocation);
        return true;
    }
Example #17
Source File: post.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
@Query(() => PagedPost)
    async [getManyPath](@Arg("pagedParams") pagedParams: PagedParamsInput<Post>,
        @Ctx() ctx: TGraphQLContext):
        Promise<TPagedList<TPost>> {
        if (!this.canGetDraft(ctx)) {
            // No auth, return only published posts
            return this.repository.getFilteredPosts(pagedParams, {
                published: true
            });
        }
        return this.repository.getPosts(pagedParams);
    }
Example #18
Source File: message-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit({ limit: 1000 }))
  @Mutation(() => Message)
  async deleteMessage(
    @Arg("messageId") messageId: ObjectID,
    @Ctx() context: Context,
    @PubSub() pubsub: PubSubEngine
  ) {
    try {
      const message = await MessageModel.findOneAndDelete({
        _id: messageId,
        author: context.currentUser.id,
      });

      if (!message) throw new ApolloError("Cannot find message with ID");

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

      return message;
    } catch (err) {
      throw new ApolloError(err);
    }
  }
Example #19
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 #20
Source File: message-subscriptions.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Subscription(returns => Message, {
    topics: CONSTANTS.NEW_MESSAGE,
    filter: filterRoom,
  })
  onNewMessage(
    @Root() message: Message,
    @Arg("roomId") roomId: ObjectID
  ): Message {
    return message;
  }
Example #21
Source File: User.resolver.ts    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
/**
   * User 정보를 삭제합니다.
   *
   * @author BounceCode, Inc.
   */
  @Mutation(() => Boolean)
  async deleteUser(@Arg('where') where: UserWhereInput) {
    try {
      return await UserEntity.delete(where);
    } catch (e) {
      console.log(e);
    }
  }
Example #22
Source File: post.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
@Authorized<TAuthRole>("administrator", 'author')
    @Mutation(() => Boolean)
    async [deleteManyFilteredPath](
        @Arg("input") input: DeleteManyInput,
        @Arg("filterParams", { nullable: true }) filterParams?: PostFilterInput,
    ): Promise<boolean | undefined> {
        const res = await this.repository.deleteManyFilteredPosts(input, filterParams);
        resetAllPagesCache();
        return res;
    }
Example #23
Source File: User.resolver.ts    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
/**
   * User 정보 목록을 가져옵니다.
   *
   * @author BounceCode, Inc.
   */
  @Query(() => [UserObject])
  async users(
    @Arg('where', {nullable: true}) where: UserWhereInput,
    @Arg('skip', () => Int) skip: number,
    @Arg('take', () => Int) take: number,
  ) {
    try {
      return await UserEntity.find({
        where,
        skip,
        take,
      });
    } catch (e) {
      console.log(e);
    }
  }
Example #24
Source File: product-category.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", { nullable: true }) filterParams?: ProductCategoryFilterInput,
    ): Promise<boolean | undefined> {
        const res = await this.repository.deleteManyCategories(input, filterParams);
        resetAllPagesCache();
        return res;
    }
Example #25
Source File: Config.resolver.ts    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Config 목록을 조회합니다.
   *
   * @author BounceCode, Inc.
   */
  @Query(() => [ConfigObject])
  async configs(@Arg('where') where: ConfigWhereInput) {
    return await ConfigEntity.find({...where, deletedBy: null});
  }
Example #26
Source File: message-subscriptions.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Subscription(returns => Message, {
    topics: CONSTANTS.DELETE_MESSAGE,
    filter: filterRoom,
  })
  onDeleteMessage(
    @Root() message: Message,
    @Arg("roomId") roomId: ObjectID
  ): Message {
    return message;
  }
Example #27
Source File: user.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", { nullable: true }) filterParams?: UserFilterInput,
    ): Promise<boolean | undefined> {
        const res = await this.repository.deleteManyFilteredUsers(input, filterParams);
        resetAllPagesCache();
        return res;
    }
Example #28
Source File: CommentEmotion.resolver.ts    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
@Query(() => CommentEmotionObject, {nullable: true})
  async commentMyEmotion(
    @Arg('where') where: CommentUniqueWhereInput,
    @Ctx() ctx: Context,
  ) {
    try {
      const userId = ctx.user.id;
      const commentId = where.id;

      const commentEmotion = await getRepository(CommentEmotionEntity)
        .createQueryBuilder('commentEmotion')
        .where('commentEmotion.userId = :userId', {userId})
        .andWhere('commentEmotion.commentId = :commentId', {commentId})
        .getOne();

      return commentEmotion;
    } catch (e) {
      console.log(e);
      return new ApolloError(e);
    }
  }
Example #29
Source File: message-subscriptions.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Subscription(returns => Message, {
    topics: CONSTANTS.UPDATE_MESSAGE,
    filter: filterRoom,
  })
  onUpdateMessage(
    @Root() message: Message,
    @Arg("roomId") roomId: ObjectID
  ): Message {
    return message;
  }