type-graphql#Query TypeScript Examples

The following examples show how to use type-graphql#Query. 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: plugin-newsletter.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
/** Restrict via decorator: */
    @Authorized<TAuthRole>("administrator", 'guest')
    @Query(() => String)
    async pluginNewsletterStats(@Ctx() ctx: TGraphQLContext): Promise<string> {
        
        // Or via checking manually user info: (both methods can work independently)
        if (ctx.user?.role !== 'administrator')
            throw new UnauthorizedException('Forbidden');

        return (await getManager().find(PluginNewsletter) ?? []).length + '';
    }
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: 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 #4
Source File: DepartmentService.ts    From graphql-ts-client with MIT License 6 votes vote down vote up
@Query(() => DepartmentConnection)
    async findDepartmentsLikeName(
        @Arg("name", () => String, {nullable: true}) name?: string | null,
        @Arg("first", () => Int, {nullable: true}) first?: number | null,
        @Arg("after", () => String, {nullable: true}) after?: string | null,
        @Arg("last", () => Int, {nullable: true}) last?: number | null,
        @Arg("before", () => String, {nullable: true}) before?: string | null
    ): Promise<DepartmentConnection> {

        /*
         * Mock the network delay
         */
        await delay(1000);

        const lowercaseName = name?.toLocaleLowerCase();
        const predicate: Predicate<TDepartment> | undefined = 
            lowercaseName !== undefined && lowercaseName !== "" ?
            d => d.name.toLowerCase().indexOf(lowercaseName) !== -1 :
            undefined
        const departments = departmentTable
            .find([], predicate)
            .map(row => new Department(row))
            .sort((a, b) => a.name > b.name ? + 1 : a.name < b.name ? -1 :0);
        return createConnection<DepartmentConnection, DepartmentEdge, Department>({
            totalCount: departments.length,
            getNodes: (offset, count) => departments.slice(offset, offset + count),
            createConnection: (totalCount, edges, pageInfo) => new DepartmentConnection(totalCount, edges, pageInfo),
            createEdge: (node, cursor) => new DepartmentEdge(node, cursor),
            first,
            after,
            last,
            before
        });
    }
Example #5
Source File: user.ts    From lireddit with MIT License 6 votes vote down vote up
@Query(() => User, { nullable: true })
  me(@Ctx() { req }: MyContext) {
    // you are not logged in
    if (!req.session.userId) {
      return null;
    }

    return User.findOne(req.session.userId);
  }
Example #6
Source File: ChatRoom.resolver.ts    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
@Query(() => [ChatRoomObject])
  async chatRooms(
    @Arg('where') where: ChatRoomWhereInput,
    @Arg('skip', {nullable: true}) skip: number = 0,
    @Arg('take', {nullable: true}) take: number = 10,
    @Ctx() ctx: Context,
  ) {
    const userId = ctx.user.id;

    const queryBuilder = getRepository(UserEntity)
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.chatRooms', 'chatRooms')
      .andWhere('user.id = :userId', {
        userId: userId,
      });

    if (where.category) {
      queryBuilder
        .leftJoinAndSelect('chatRooms.category', 'category')
        .andWhere('category.id = :categoryId', {
          categoryId: where.category,
        });
    }

    const result = await queryBuilder
      .offset(skip)
      .limit(take)
      .getMany();

    console.log(result);

    return result;
  }
Example #7
Source File: fields.ts    From backend with MIT License 6 votes vote down vote up
@Query(returns => School, { nullable: true })
    @Authorized(Role.UNAUTHENTICATED)
    @LimitedQuery()
    async schoolForTeacherEmail(@Arg("teacherEmail") teacherEmail: string) {
        const email = new Address(teacherEmail);

        const school = await prisma.school.findFirst({
            where: {
                emailDomain: email.host
            }
        });

        return school;
    }
Example #8
Source File: author.resolver.ts    From mikro-orm-graphql-example with MIT License 6 votes vote down vote up
@Query(() => Author, { nullable: true })
  public async getAuthor(
    @Arg('id') id: string,
    @Ctx() ctx: MyContext,
    @Info() info: GraphQLResolveInfo,
  ): Promise<Author | null> {
    const relationPaths = fieldsToRelations(info);
    return ctx.em.getRepository(Author).findOne({ id }, relationPaths);
  }
Example #9
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 #10
Source File: config.resolver.ts    From liferay-grow with MIT License 6 votes vote down vote up
@Query(() => Configuration, { name: `getServerInfo` })
  getConfig(): Configuration {
    const { APP_NAME = 'Liferay Grow' } = process.env;

    const { version: SERVER_VERSION } = PKG;

    return {
      SERVER_NAME: APP_NAME,
      SERVER_VERSION,
    };
  }
Example #11
Source File: resolvers.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
@Query(() => [ScalarRow])
    async scalarsExtension(): Promise<ScalarRow[]>  {
        let em = await this.tx()
        return em.find(Scalar, {
            order: {
                id: 'ASC'
            }
        })
    }
Example #12
Source File: plugin-newsletter.resolver.ts    From Cromwell with MIT License 5 votes vote down vote up
@Authorized<TAuthRole>("administrator", 'guest')
    @Query(() => [PluginNewsletter])
    async pluginNewsletterExport(): Promise<PluginNewsletter[]> {
        return await getManager().find(PluginNewsletter);
    }
Example #13
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 #14
Source File: resolver.ts    From typegraphql-nestjs with MIT License 5 votes vote down vote up
@Query(returns => [Recipe])
  recipes() {
    return this.recipeService.getRecipes();
  }
Example #15
Source File: user-resolver.ts    From convoychat with GNU General Public License v3.0 5 votes vote down vote up
@Authorized()
  @Query(() => Me)
  me(@Ctx() context: Context): Me {
    return context.getUser();
  }
Example #16
Source File: EmployeeService.ts    From graphql-ts-client with MIT License 5 votes vote down vote up
@Query(() => EmployeeConnection)
    async findEmployees(
        @Arg("name", () => String, {nullable: true}) name?: string | null,
        @Arg("departmentId", () => String, {nullable: true}) departmentId?: string | null,
        @Arg("supervisorId", () => String, {nullable: true}) supervisorId?: string | null,
        @Arg("mockedErrorProbability", () => Int, {nullable: true}) mockedErrorProbability?: number | null,
        @Arg("first", () => Int, {nullable: true}) first?: number | null,
        @Arg("after", () => String, {nullable: true}) after?: string | null,
        @Arg("last", () => Int, {nullable: true}) last?: number | null,
        @Arg("before", () => String, {nullable: true}) before?: string | null
    ): Promise<EmployeeConnection> {

        /*
         * Mock the network delay
         */
        await delay(1000);

        /*
         * Mock the network error
         */
        if (mockedErrorProbability !== undefined && mockedErrorProbability !== null && mockedErrorProbability > 0) {
            const top = Math.min(mockedErrorProbability, 100);
            if (Math.floor(Math.random() * 100) < top) {
                throw new Error(`Mocked error by nodejs at '${Date()}'`);
            }
        }
        
        const lowercaseName = name?.toLocaleLowerCase();
        const employees = employeeTable
            .find(
                [
                    departmentId !== undefined && departmentId !== null ? 
                    { prop: "departmentId", value: departmentId } :
                    undefined,
                    supervisorId !== undefined && supervisorId !== null ? 
                    { prop: "supervisorId", value: supervisorId } :
                    undefined,
                ], 
                lowercaseName !== undefined && lowercaseName !== "" ?
                d => (
                    d.firstName.toLowerCase().indexOf(lowercaseName) !== -1 ||
                    d.lastName.toLowerCase().indexOf(lowercaseName) !== -1
                ) :
                undefined
            )
            .map(row => new Employee(row))
            .sort((a, b) => a.firstName > b.firstName ? + 1 : a.firstName < b.firstName ? -1 :0);
        return createConnection<EmployeeConnection, EmployeeEdge, Employee>({
            totalCount: employees.length,
            getNodes: (offset, count) => employees.slice(offset, offset + count),
            createEdge: (node, cursor) => new EmployeeEdge(node, cursor),
            createConnection: (totalCount, edges, pageInfo) => new EmployeeConnection(totalCount, edges, pageInfo),
            first,
            after,
            last,
            before
        });
    }
Example #17
Source File: hello.ts    From lireddit with MIT License 5 votes vote down vote up
@Query(() => String)
  hello() {
    return "bye";
  }