How to use the type-graphql.UseMiddleware 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 wemaintain / auto-relay / packages / core / src / services / relay-query.service.ts View on Github external
RelayedQueryTypedDescriptor<
        Through extends (undefined | null) ? Model : Through,
        Through extends (undefined | null) ? never : true
      >
    >,
    to: ClassValueThunk, 
    through?: ClassValueThunk,
    options?: RelayedQueryOptions,
    isFieldResolver: boolean = false
  ): void {
    const queryName = this.getQueryName(propertyKey, options)
    const { Connection } = this.makeEdgeConnection(to, through)
    this.registerArgs(target, propertyKey, options)

    const middleware = RelayFromArrayCountFactory(target, propertyKey);
    UseMiddleware(middleware)(target, propertyKey, descriptor)
    if(isFieldResolver) {
      FieldResolver(() => Connection, { ...options, name: queryName })(target, propertyKey, descriptor)
    } else {
      Query(() => Connection, { ...options, name: queryName })(target, propertyKey, descriptor)
    }
  }
github kevenleone / graphscript / src / utils / createBaseResolver.ts View on Github external
@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}` })
    async createMulti(@Arg('data', () => [inputTypes.create]) data: any[]): Promise {
      const promises = data.map(obj => entity.create(obj).save());
      const insertedData = await Promise.all(promises);
      return insertedData;
    }

    @UseMiddleware(isAuth)
    @Mutation(() => Boolean, { name: `deleteBy${suffix}ID` })
    async deleteByID(@Arg('id', () => String) id: string): Promise {
      const _entity = await this.get(id);
      if (!_entity) {
        sendError(`No data found on Entity: ${suffix}, ID: ${id}`);
      }
      const data = await entity.remove(_entity);
      if (middlewares && middlewares.delete.after) {
        await middlewares.delete.after(id);
      }

      return !!data;
    }

    async update(data: any, entityData: any): Promise {
      for (const field in data) {
github benawad / type-graphql-series / src / modules / user / Register.ts View on Github external
import { Resolver, Query, Mutation, Arg, UseMiddleware } from "type-graphql";
import bcrypt from "bcryptjs";

import { User } from "../../entity/User";
import { RegisterInput } from "./register/RegisterInput";
import { isAuth } from "../middleware/isAuth";
import { logger } from "../middleware/logger";
import { sendEmail } from "../utils/sendEmail";
import { createConfirmationUrl } from "../utils/createConfirmationUrl";

@Resolver()
export class RegisterResolver {
  @UseMiddleware(isAuth, logger)
  @Query(() => String)
  async hello() {
    return "Hello World!";
  }

  @Mutation(() => User)
  async register(@Arg("data")
  {
    email,
    firstName,
    lastName,
    password
  }: RegisterInput): Promise {
    const hashedPassword = await bcrypt.hash(password, 12);

    const user = await User.create({
github benawad / codeponder / packages / server / src / modules / notifications / resolver.ts View on Github external
commentId,
        questionId,
        userToNotifyId: req.session && req.session.userId,
      },
      {
        read,
      }
    );

    return {
      ok: true,
    };
  }

  @Mutation(() => OkResponse)
  @UseMiddleware(isAuthenticated)
  async markAllNotificationsAsRead(@Ctx() { req }: MyContext): Promise<
    OkResponse
  > {
    await this.questionCommentNotificationRepo.update(
      {
        userToNotifyId: req.session && req.session.userId,
      },
      {
        read: true,
      }
    );

    return {
      ok: true,
    };
  }
github birkir / prime / packages / prime-core / src / modules / internal / utils / Authorized.ts View on Github external
export function Authorized(ruleFn?: any) {
  return UseMiddleware(
    async ({ args, context, info }: { args: any; context: Context; info: any }, next) => {
      const { session = {} } = info || {};
      if (!context.user && !session.user) {
        throw new AuthenticationError('Must be authenticated');
      }

      if (ruleFn) {
        ruleFn(
          {
            can: (action: string, subject: any, field?: string) => {
              context.ability.throwUnlessCan(action, subject, field);
            },
          },
          args
        );
      }
github kevenleone / graphscript / src / utils / createBaseResolver.ts View on Github external
export function createBaseResolver(
  suffix: string,
  entity: any,
  inputTypes: { create: classType; update: classType; filter?: classType },
  returnType: classType,
  middlewares?: MiddlewareBaseResolver
): any {
  @Resolver({ isAbstract: true })
  abstract class BaseResolver {
    @UseMiddleware(isAuth)
    @Query(() => [returnType], { name: `getAll${suffix}` })
    async getAll(): Promise {
      return entity.find();
    }

    @UseMiddleware(isAuth)
    @Query(() => [returnType], { name: `getAll${suffix}Filter` })
    async getAllFiltered(@Arg('data', () => inputTypes.filter || inputTypes.create) data: any): Promise {
      return entity.find({ where: data });
    }

    @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 });
github kevenleone / graphscript / src / utils / createBaseResolver.ts View on Github external
): any {
  @Resolver({ isAbstract: true })
  abstract class BaseResolver {
    @UseMiddleware(isAuth)
    @Query(() => [returnType], { name: `getAll${suffix}` })
    async getAll(): Promise {
      return entity.find();
    }

    @UseMiddleware(isAuth)
    @Query(() => [returnType], { name: `getAll${suffix}Filter` })
    async getAllFiltered(@Arg('data', () => inputTypes.filter || inputTypes.create) data: any): Promise {
      return entity.find({ where: data });
    }

    @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) {
github benawad / codeponder / packages / server / src / modules / notifications / resolver.ts View on Github external
import { QuestionCommentNotification } from "../../entity/QuestionCommentNotification";
import { MyContext } from "../../types/Context";
import { isAuthenticated } from "../shared/middleware/isAuthenticated";
import { OkResponse } from "../shared/OkResponse";
import { NotificationsResponse } from "./response";

const NOTIF_LIMIT = 50;
@Resolver(Comment)
export class CommentResolver {
  @InjectRepository(QuestionCommentNotification)
  private readonly questionCommentNotificationRepo: Repository<
    QuestionCommentNotification
  >;

  @Query(() => NotificationsResponse)
  @UseMiddleware(isAuthenticated)
  async notifications(
    @Ctx() { req }: MyContext,
    @Arg("cursor", { nullable: true }) cursor?: string
  ): Promise {
    const where: FindOneOptions["where"] = {
      userToNotifyId: req.session && req.session.userId,
    };

    if (cursor) {
      where.createdAt = LessThan(cursor);
    }

    const notifs = await this.questionCommentNotificationRepo.find({
      where,
      relations: ["comment", "question", "question.post"],
      order: { read: "ASC", createdAt: "DESC" },
github benawad / codeponder / packages / server / src / modules / post / resolver.ts View on Github external
import { isAuthenticated } from "../shared/middleware/isAuthenticated";
import { CreatePostInput } from "./createInput";
import { FindPostInput } from "./findInput";
import { FindPostResponse } from "./findResponse";
import { PostResponse } from "./response";

const POST_LIMIT = 6;
@Resolver(Post)
export class PostResolvers {
  @InjectRepository(QuestionRepository)
  private readonly questionRepo: QuestionRepository;
  @InjectRepository(PostRepository)
  private readonly postRepo: PostRepository;

  @Mutation(() => PostResponse)
  @UseMiddleware(isAuthenticated)
  async findOrCreatePost(
    @Arg("post") input: CreatePostInput,
    @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,
        creatorId: req.session && req.session.userId,
github developer239 / node-type-orm-graphql / src / modules / Core / resolvers / createResolver.ts View on Github external
export const createResolver = (
  entity: any,
  inputType: IInputType,
  middleware?: Middleware[]
) => {
  @Resolver()
  class BaseResolver {
    @Mutation(() => entity, { name: `create${entity.className}` })
    @UseMiddleware(...(middleware || []))
    create(@Arg('data', () => inputType) data: any, @Ctx() ctx: IAppContext) {
      if (entity.belongsToUser) {
        return entity
          .create({
            ...data,
            userConnection: { id: ctx.req.session.userId },
          })
          .save()
      }

      return entity.create(data).save()
    }
  }

  return BaseResolver
}