How to use @nestjs/graphql - 10 common examples

To help you get started, we’ve selected a few @nestjs/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 jmcdo29 / testing-nestjs / apps / typeorm-graphql-sample / src / app.module.ts View on Github external
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CatModule } from './cat/cat.module';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      url: process.env.DATABASE_URL,
      synchronize: true,
      entities: [__dirname + '/**/*.entity.{ts,js}'],
    }),
    GraphQLModule.forRoot({
      debug: true,
      playground: true,
      typePaths: ['./**/*.graphql'],
      installSubscriptionHandlers: true,
      // context: ({req}) => {
      // return {req};
      // },
    }),
    CatModule,
  ],
})
export class AppModule {}
github jmcdo29 / testing-nestjs / apps / typeorm-graphql-sample / src / graphql / generate-typings.ts View on Github external
import { GraphQLDefinitionsFactory } from '@nestjs/graphql';
import { join } from 'path';

const definitionsFactory = new GraphQLDefinitionsFactory();

// tslint:disable-next-line: no-floating-promises
definitionsFactory.generate({
  typePaths: ['./src/**/*.graphql'],
  path: join(process.cwd(), 'src/graphql/protocol.schema.ts'),
  outputAs: 'class',
});
github chnirt / nestjs-graphql-best-practice / src / resolvers / auth.resolver.ts View on Github external
return await tradeToken(user)
		}

		if (info) {
			// console.log(info)
			const { code } = info
			switch (code) {
				case 'ETIMEDOUT':
					throw new ApolloError('Failed to reach Google: Try Again')
				default:
					throw new ApolloError('Something went wrong')
			}
		}
	}

	@Mutation()
	async oauthGoogle(
		@Args('accessToken') accessToken: string,
		@Context() context: any
	): Promise {
		const { req, res } = context

		req.body = {
			...req.body,
			access_token: accessToken,
		}

		const { data, info } = await authenticateGoogle(req, res)

		if (data) {
			console.log(data.profile)
github chnirt / nestjs-graphql-best-practice / src / resolvers / user.resolver.ts View on Github external
// 	return user
	// }

	@Subscription(() => Object, {
		filter: (payload: any, variables: any) => {
			// console.log('payload', payload)
			// console.log('variables', variables)
			// return payload.menuPublishByOrder.currentsite === variables.currentsite
			return true
		}
	})
	async newUser(@Context('pubsub') pubsub: any): Promise {
		return pubsub.asyncIterator(USER_SUBSCRIPTION)
	}

	@ResolveProperty()
	async fullName(@Parent() user: User): Promise {
		const { firstName, lastName } = user
		return `${firstName} ${lastName}`
	}

	// @ResolveProperty()
	// async local(@Parent() user: User): Promise {
	// 	const { local } = user
	// 	local.password = ''
	// 	return local
	// }

	@Mutation()
	async validateUser(
		@Args('text') text: string,
		@Args('input') input: CreateUserInput
github magishift / magishift.core / src / auth / role / roles.guard.ts View on Github external
const rolePermissions: string[] =
        this.reflector.get('roles', context.getHandler()) ||
        this.reflector.get('roles', context.getClass());

      const realmPermissions: string[] =
        this.reflector.get('realm', context.getHandler()) ||
        this.reflector.get('realm', context.getClass());

      const isPublic =
        !rolePermissions || rolePermissions.length === 0 || rolePermissions.indexOf(DefaultRoles.public) >= 0;

      // Get request data
      let request = context.switchToHttp().getRequest();

      if (!request) {
        const ctx = GqlExecutionContext.create(context);
        request = ctx.getContext().req;
      }

      const headerRealm: string = request.headers.realm || request.query.realm;
      if (!isPublic && !headerRealm) {
        throw new HttpException('Resource is not public, you must provide "realm" in request headers', 400);
      }

      const headerAuth: string[] = request.headers.authorization
        ? request.headers.authorization.split(' ')
        : [request.query.token];

      if (headerAuth && headerAuth.length > 0 && headerRealm) {
        const jwtToken = headerAuth[headerAuth.length - 1] || request.query.token;

        if (realmPermissions && realmPermissions.length > 0 && realmPermissions.indexOf(headerRealm) === -1) {
github jkchao / blog-service / src / module / heros / heros.resolvers.ts View on Github external
public getHeros(@Args() args: QueryHerosDto, @Context('request') request: Request) {
    const token = request.headers.authorization;
    if (!token) {
      args.state = 1;
    }
    return this.herosService.searchHero(args);
  }

  @Mutation()
  @Permissions()
  public async deleteHero(@Args('_id') _id: string) {
    await this.herosService.deleteHero(_id);
    return { message: 'success' };
  }

  @Mutation()
  @Permissions()
  public async createHero(@Args('heroInfo') info: HerosInfoDto, @Context('request') request: Request) {
    // 获取ip地址以及物理地理地址
    const ip = ((request.headers['x-forwarded-for'] ||
      request.headers['x-real-ip'] ||
      request.connection.remoteAddress ||
      request.socket.remoteAddress ||
      request.ip ||
      request.ips[0]) as string).replace('::ffff:', '');

    info.ip = ip;
    info.agent = request.headers['user-agent'] || info.agent;

    const result = await this.herosService.createHero({ ...info, ip });

    this.emailService.sendEmail({
github juicycleff / ultimate-backend / apps / service-auth / src / roles / roles.resolver.ts View on Github external
@Resolver(() => Role)
export class RolesResolver {
  constructor(private readonly casbinService: NestCasbinService) {}

  @Query(() => [Role])
  async roles() {
    throw new NotImplementedError('Not implemented');
  }

  @Query(() => Role)
  async role(@Args('id') id: string) {
    throw new NotImplementedError('Not implemented');
  }

  @Mutation(() => Role, { name: 'role'})
  async roleMutation(@Args() cmds: RoleMutationArgs) {
   //  const actions = this.casbinService.addPolicy('juicycleff', 'tenantx', 'project/001', 'read');
    throw new NotImplementedError('Not implemented');
  }
}
github SolidZORO / leaa / packages / leaa-api / src / modules / category / category.resolver.ts View on Github external
}

  // @UseGuards(PermissionsGuard)
  // @Permissions('category.item-read')
  // DO NOT CHECK PERMISSIONS
  @Query(() => Category)
  async category(
    @Args({ name: 'id', type: () => Int }) id: number,
    @Args() args?: CategoryArgs,
  ): Promise {
    return this.categoryService.category(id, args);
  }

  @UseGuards(PermissionsGuard)
  @Permissions('category.item-create')
  @Mutation(() => Category)
  async createCategory(@Args('category') args: CreateCategoryInput): Promise {
    return this.categoryService.createCategory(args);
  }

  @UseGuards(PermissionsGuard)
  @Permissions('category.item-update')
  @Mutation(() => Category)
  async updateCategory(
    @Args({ name: 'id', type: () => Int }) id: number,
    @Args('category') args: UpdateCategoryInput,
  ): Promise {
    return this.categoryService.updateCategory(id, args);
  }

  @UseGuards(PermissionsGuard)
  @Permissions('category.item-delete')
github juicycleff / ultimate-backend / libs / nestjs-graphql-gateway / src / services / references-explorer.service.spec.ts View on Github external
/* tslint:disable:max-classes-per-file */
import { INestApplicationContext, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { MetadataScanner } from '@nestjs/core/metadata-scanner';
import { Resolver } from '@nestjs/graphql';
import { GRAPHQL_MODULE_OPTIONS } from '@nestjs/graphql/dist/graphql.constants';
import { ResolveReference } from '../decorators';
import { ReferencesExplorerService } from './references-explorer.service';

@Resolver()
class AccountsResolver {
  @Resolver('User')
  @ResolveReference()
  // tslint:disable-next-line
  public user() {}
}

@Module({
  providers: [
    {
      provide: GRAPHQL_MODULE_OPTIONS,
      useValue: {},
    },
    AccountsResolver,
    MetadataScanner,
    ReferencesExplorerService,
  ],
})
github SolidZORO / leaa / packages / leaa-api / src / modules / user / user.resolver.ts View on Github external
} from '@leaa/common/src/dtos/user';
import { UserService } from '@leaa/api/src/modules/user/user.service';
import { UserProperty } from '@leaa/api/src/modules/user/user.property';
import { CurrentUser, Permissions } from '@leaa/api/src/decorators';
import { PermissionsGuard } from '@leaa/api/src/guards';

@Resolver(() => User)
export class UserResolver {
  constructor(private readonly userService: UserService, private readonly userProperty: UserProperty) {}

  @ResolveProperty(() => [String])
  async flatPermissions(@Parent() user: User | undefined): Promise {
    return this.userProperty.flatPermissions(user);
  }

  @ResolveProperty(() => [String])
  async permissions(@Parent() user: User | undefined): Promise {
    return this.userProperty.permissions(user);
  }

  //

  // fot Test GraphQL
  @Query(() => Float)
  async ram(): Promise {
    return Math.random();
  }

  @UseGuards(PermissionsGuard)
  @Permissions('user.list-read')
  @Query(() => UsersWithPaginationObject)
  async users(@Args() args: UsersArgs, @CurrentUser() user?: User): Promise {