@nestjs/graphql#Resolver TypeScript Examples
The following examples show how to use
@nestjs/graphql#Resolver.
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: form.statistic.resolver.ts From api with GNU Affero General Public License v3.0 | 6 votes |
@Resolver(() => FormStatisticModel)
export class FormStatisticResolver {
constructor(
private readonly statisticService: FormStatisticService,
) {
}
@ResolveField(() => Int)
@Roles('admin')
total(): Promise<number> {
return this.statisticService.getTotal()
}
}
Example #2
Source File: connectorRestApi.resolver.ts From amplication with Apache License 2.0 | 6 votes |
@Resolver(() => ConnectorRestApi)
export class ConnectorRestApiResolver extends BlockTypeResolver(
ConnectorRestApi,
'ConnectorRestApis',
FindManyConnectorRestApiArgs,
'createConnectorRestApi',
CreateConnectorRestApiArgs,
'updateConnectorRestApi',
UpdateBlockArgs
) {
constructor(private readonly service: ConnectorRestApiService) {
super();
}
}
Example #3
Source File: users.resolver.ts From knests with MIT License | 6 votes |
@Resolver('User')
export class UsersResolver {
constructor(
private readonly usersService: UsersService,
) {}
@Query('user')
async getUser(@Args('userId', ParseUUIDPipe) userId: string) {
return this.usersService.findById(userId);
}
@ResolveField()
async roles(@Parent() user) {
return user.roles || [];
}
@Mutation('signup')
async signup(@Args('user') user: UserSignupDTO) {
return this.usersService.signup(user);
}
}
Example #4
Source File: app.resolver.ts From nestjs-jaeger-tracing with MIT License | 6 votes |
@Resolver()
export class AppResolver {
constructor(private readonly appService: AppService) {}
@Query('getHello')
hello(@Tracing() tracing: TracingData): string {
Logger.log({ getHello: tracing });
return this.appService.getHello();
}
@Mutation('echoMessage')
replyMessage(
@Tracing() tracing: TracingData,
@Args('message') message: string,
): Observable<string> {
Logger.log({ echoMessage: tracing });
return this.appService.echoMessage(message);
}
}
Example #5
Source File: auth.resolver.ts From knests with MIT License | 6 votes |
@Resolver('Auth')
export class AuthResolver {
constructor(
private readonly authService: AuthService,
) {}
@Mutation('login')
async login(@Args('user') user: LoginDTO){
const jwtToken = await this.authService.login(user);
if(!jwtToken) throw new UnauthorizedException();
return jwtToken;
}
}
Example #6
Source File: notification.resolver.ts From aws-nestjs-starter with The Unlicense | 6 votes |
@Resolver(() => Notification)
export class NotificationResolver {
constructor(private readonly notificationService: NotificationService) {}
@Mutation(/* istanbul ignore next */ () => Notification)
createNotification(@Args('input') input: CreateNotificationInput) {
return this.notificationService.create(input);
}
@Mutation(/* istanbul ignore next */ () => Notification)
updateNotification(
@Args('id', { type: /* istanbul ignore next */ () => ID }) id: string,
@Args('input') input: UpdateNotificationInput,
) {
return this.notificationService.update({ id }, input);
}
@Query(/* istanbul ignore next */ () => Notification)
notification(
@Args('id', { type: /* istanbul ignore next */ () => ID }) id: string,
) {
return this.notificationService.findOne({ id });
}
@Query(/* istanbul ignore next */ () => [Notification])
notificationByUserId(@Args('userId') userId: string) {
return this.notificationService.findByUserId(userId);
}
@Query(/* istanbul ignore next */ () => [Notification])
notificationByTargetId(@Args('targetId') targetId: string) {
return this.notificationService.findByTargetId(targetId);
}
}
Example #7
Source File: user.resolver.ts From NextJS-NestJS-GraphQL-Starter with MIT License | 6 votes |
@Resolver(() => User)
export class UserResolver {
constructor(private userService: UserService) {}
@UseGuards(AuthGuard)
@Mutation(() => User)
async updateUser(@Args('input') input: UpdateUserInput, @Context() context) {
const userId = get(context, 'req.user._id');
return this.userService.updateById({ userId, input: deepClean(input) });
}
@Query(() => [User])
async users() {
return this.userService.findAll();
}
@Query(() => User, { nullable: true })
async me(@Context() context) {
return this.userService.findOne({ _id: context.req.user });
}
@Query(() => User, { nullable: true })
async user(@Args('input') input: GetUserInput) {
return this.userService.findOne({ permalink: input.userPermalink });
}
}
Example #8
Source File: ship.resolver.ts From nestjs-relay with MIT License | 6 votes |
@Resolver(Ship)
export class ShipResolver extends GlobalIdFieldResolver(Ship) {
constructor(private shipService: ShipService, private factionService: FactionService) {
super();
}
@RelayMutation(() => IntroduceShipOutput, {
name: 'introduceShip',
})
introduceShip(
@InputArg(() => IntroduceShipInput) input: IntroduceShipInput,
): IntroduceShipOutput | null {
const data = this.factionService.introduceShipToFaction(
input.factionId.toString(),
input.shipName,
);
if (!data) return null;
return new IntroduceShipOutput(data);
}
}
Example #9
Source File: cat.resolver.ts From nestjs-mercurius with MIT License | 6 votes |
@Resolver(() => Cat)
export class CatResolver {
constructor(private readonly catService: CatService) {}
@Query(() => [Cat])
cats() {
return this.catService.cats();
}
@Query(() => Cat, { nullable: true })
cat(@Args({ name: 'id', type: () => ID }, ParseIntPipe) id: number) {
return this.catService.cat(id);
}
@ResolveLoader(() => Boolean)
hasFur(@Parent() queries: LoaderQuery<Cat>[]) {
return queries.map(({ obj }) => obj.lives > 1);
}
@Subscription(() => Cat, {
resolve: (payload) => payload,
})
onCatSub(@Context('pubsub') pubSub: PubSub) {
return toAsyncIterator(pubSub.subscribe('CAT_SUB_TOPIC'));
}
}
Example #10
Source File: page.resolver.ts From api with GNU Affero General Public License v3.0 | 6 votes |
@Resolver(() => PageModel)
export class PageResolver {
constructor(
private readonly idService: IdService,
) {
}
@ResolveField(() => [ButtonModel])
async buttons(
@Parent() parent: FormModel,
@Context('cache') cache: ContextCache,
): Promise<ButtonModel[]> {
if (!parent._id) {
return []
}
const page = await cache.get<PageEntity>(cache.getCacheKey(PageEntity.name, parent._id))
return page.buttons.map(button => new ButtonModel(
this.idService.encode(button.id),
button
))
}
}
Example #11
Source File: global-id-field.resolver.ts From nestjs-relay with MIT License | 6 votes |
@Resolver(classRef, { isAbstract: true })
abstract class GlobalIdFieldResolverHost {
@GlobalIdField(globalIdFieldOptions)
id(@Parent() parent: ResolverParent, @Info() info: ResolverInfo): ResolvedGlobalId {
if (!parent || !parent.id) {
throw new Error(`Cannot resolve id when 'parent' or 'parent.id' is null`);
}
switch (typeof parent.id) {
case 'object':
return parent.id;
case 'string':
return new ResolvedGlobalId({
type: info.parentType.name,
id: parent.id,
});
case 'number':
return new ResolvedGlobalId({
type: info.parentType.name,
id: parent.id.toString(),
});
}
}
}
Example #12
Source File: user.resolver.ts From nestjs-mercurius with MIT License | 6 votes |
@Resolver(() => User)
export class UserResolver {
@ResolveField(() => [Post])
posts(@Parent() user: User) {
const userPosts = posts.filter(
(p) => p.authorId.toString() === user.id.toString(),
);
return userPosts;
}
}
Example #13
Source File: find-users.graphql-resolver.ts From domain-driven-hexagon with MIT License | 6 votes |
@Resolver()
export class FindUsersGraphqlResolver {
constructor(private readonly userRepo: UserRepository) {}
@Query(() => [UserResponse])
async findUsers(
@Args('input') input: FindUsersRequest,
): Promise<UserResponse[]> {
const query = new FindUsersQuery(input);
const users = await this.userRepo.findUsers(query);
return users.map(user => new UserResponse(user));
}
}
Example #14
Source File: hello.resolver.ts From nestjs-mercurius with MIT License | 6 votes |
@Resolver()
export class HelloResolver {
static COUNTER = 0;
constructor(
private readonly helloService: HelloService,
private readonly usersService: UsersService,
) {
HelloResolver.COUNTER++;
}
@Query()
@UseGuards(Guard)
@UseInterceptors(Interceptor)
getCats(): any[] {
return this.helloService.getCats();
}
}
Example #15
Source File: webhook.resolver.ts From whispr with MIT License | 6 votes |
@Resolver(() => Webhook)
export class WebhookResolver {
constructor(private readonly webhookService: WebhookService) {}
/**
* Queries
*/
@Query(() => [Webhook], { nullable: true })
async webhooks(): Promise<IWebhook[]> {
return this.webhookService.findAll();
}
/**
* Mutations
*/
@Mutation(() => Webhook)
async createWebhook(@Args('webhook') webhook: WebhookInputType): Promise<IWebhook> {
return this.webhookService.create(webhook);
}
@Mutation(() => Boolean)
async deleteWebhook(@Args('id') id: string): Promise<boolean> {
return this.webhookService.delete(id);
}
}
Example #16
Source File: animal.resolver.ts From nestjs-mercurius with MIT License | 6 votes |
@Resolver(() => Animal)
export class AnimalResolver {
constructor(
private readonly catService: CatService,
private readonly dogService: DogService,
) {}
@Query(() => [Animal])
animals() {
return [...this.dogService.dogs(), ...this.catService.cats()];
}
@Query(() => [DomesticAnimal])
domesticAnimals(
@Args({ name: 'species', type: () => Species, nullable: true })
species?: Species,
) {
switch (species) {
case Species.DOG:
return this.dogService.dogs();
case Species.CAT:
return this.catService.cats();
default:
return [...this.dogService.dogs(), ...this.catService.cats()];
}
}
@ResolveField(() => Boolean)
hasPaws(@Parent() animal: Animal) {
return true;
}
@ResolveLoader(() => String)
aField(@Parent() queries: LoaderQuery<Animal>[]) {
return queries.map(({ obj }) => 'lorem');
}
}
Example #17
Source File: auth.resolver.ts From svvs with MIT License | 6 votes |
/**
* AuthResolver execute auth.graphql query
*/
@Resolver('Auth')
export class AuthResolver {
/**
* Inject into AuthResolver: AuthService
*
* @param authService validate user and return SignAuthResponse
*/
constructor(private readonly authService: AuthService) {}
/**
* Implement GraphQL Query 'login'
*
* @param signInPayload from lib shared-data-access-interfaces
*/
@Query('login')
async login(
@SignIn() signInPayload: ISignAuthPayload
): Promise<ISignAuthResponse> {
return await this.authService.login(signInPayload);
}
/**
* Implement GraphQL Query 'logout'
*/
@Query('logout')
async logout(): Promise<boolean> {
return true;
}
}
Example #18
Source File: auth.resolver.ts From amplication with Apache License 2.0 | 6 votes |
@Resolver(UserInfo)
export class AuthResolver {
constructor(private readonly authService: AuthService) {}
@Mutation(() => UserInfo)
async login(@Args() args: LoginArgs): Promise<UserInfo> {
return this.authService.login(args.credentials);
}
@Query(() => UserInfo)
@common.UseGuards(GqlDefaultAuthGuard, gqlACGuard.GqlACGuard)
async userInfo(@UserData() userInfo: UserInfo): Promise<UserInfo> {
return userInfo;
}
}
Example #19
Source File: post.resolver.ts From nestjs-mercurius with MIT License | 6 votes |
@Resolver(() => Post)
export class PostResolver {
@Query(() => [Post])
posts() {
return posts;
}
@ResolveField(() => User)
author(@Parent() post: Post) {
return { __typename: 'User', id: post.authorId };
}
}
Example #20
Source File: appSettings.resolver.ts From amplication with Apache License 2.0 | 6 votes |
@Resolver(() => AppSettings)
@UseGuards(GqlAuthGuard)
export class AppSettingsResolver {
constructor(private readonly service: AppSettingsService) {}
@Mutation(() => AppSettings, {
nullable: true,
description: undefined
})
@AuthorizeContext(AuthorizableResourceParameter.AppId, 'where.id')
async updateAppSettings(
@Args() args: UpdateAppSettingsArgs,
@UserEntity() user: User
): Promise<AppSettings> {
return this.service.updateAppSettings(args, user);
}
@Query(() => AppSettings, {
nullable: false
})
@AuthorizeContext(AuthorizableResourceParameter.AppId, 'where.id')
async appSettings(
@Args() args: FindOneArgs,
@UserEntity() user: User
): Promise<AppSettings> {
return this.service.getAppSettingsBlock(args, user);
}
}
Example #21
Source File: person.resolver.ts From nestjs-mercurius with MIT License | 6 votes |
@Resolver(() => Person)
export class PersonResolver {
@ResolveField(() => String)
uniqueName(@Parent() person: Person) {
return `${person.id}__${person.name}`;
}
@ResolveLoader(() => String)
uniqueId(@Parent() queries: LoaderQuery<Person>[]) {
return queries.map(({ obj }) => `${obj.name}__${obj.id}`);
}
}
Example #22
Source File: block.resolver.ts From amplication with Apache License 2.0 | 5 votes |
/** @todo add FieldResolver to return the settings, inputs, and outputs from the current version */
@Resolver(() => Block)
@UseFilters(GqlResolverExceptionsFilter)
@UseGuards(GqlAuthGuard)
export class BlockResolver {
constructor(
private readonly blockService: BlockService,
private readonly userService: UserService
) {}
@Query(() => [Block], {
nullable: false,
description: undefined
})
@AuthorizeContext(AuthorizableResourceParameter.AppId, 'where.app.id')
async blocks(@Args() args: FindManyBlockArgs): Promise<Block[]> {
return this.blockService.findMany(args);
}
@Query(() => Block, {
nullable: false,
description: undefined
})
@AuthorizeContext(AuthorizableResourceParameter.BlockId, 'where.id')
async block(@Args() args: FindOneArgs): Promise<Block> {
return this.blockService.block(args);
}
//resolve the parentBlock property as a generic block
@ResolveField(() => Block, { nullable: true })
async parentBlock(@Parent() block: Block): Promise<Block> {
return this.blockService.getParentBlock(block);
}
@ResolveField(() => [BlockVersion])
async versions(
@Parent() entity: Block,
@Args() args: FindManyBlockVersionArgs
): Promise<BlockVersion[]> {
return this.blockService.getVersions({
...args,
where: {
...args.where,
block: { id: entity.id }
}
});
}
@ResolveField(() => [User])
async lockedByUser(@Parent() block: Block): Promise<User> {
if (block.lockedByUserId) {
return this.userService.findUser({
where: {
id: block.lockedByUserId
}
});
} else {
return null;
}
}
}
Example #23
Source File: search.resolver.ts From nestjs-mercurius with MIT License | 5 votes |
@Resolver()
export class SearchResolver {
@Query(() => [SearchUnion])
search() {
return [...users, ...posts];
}
}
Example #24
Source File: global-id-field.resolver.spec.ts From nestjs-relay with MIT License | 5 votes |
@Resolver(Type)
export class TypeResolver extends GlobalIdFieldResolver(Type) {}
Example #25
Source File: user.resolver.ts From nestjs-mercurius with MIT License | 5 votes |
@Resolver(() => User)
export class UserResolver {
@Query(() => [User])
users() {
return users;
}
@ResolveReferenceLoader()
resolveReference(refs: LoaderQuery<Reference<'User', 'id'>>[]) {
const refIds = refs.map(({ obj }) => obj.id.toString());
return users.filter((u) => refIds.includes(u.id.toString()));
}
@Mutation(() => User)
createUser(
@Args('input') data: CreateUserInput,
@Context('pubsub') pubSub: PubSub,
) {
const user = {
...data,
id: nextId,
};
users.push(user);
pubSub.publish({
topic: 'createUser',
payload: { user },
});
nextId++;
return user;
}
@Subscription(() => User, {
resolve: (payload) => payload.user,
})
onCreateUser(@Context('pubsub') pubSub: PubSub) {
return toAsyncIterator(pubSub.subscribe('createUser'));
}
}
Example #26
Source File: submission.progress.resolver.ts From api with GNU Affero General Public License v3.0 | 5 votes |
@Resolver(() => SubmissionProgressModel)
export class SubmissionProgressResolver {
}
Example #27
Source File: global-id-field.resolver.ts From nestjs-relay with MIT License | 5 votes |
export function GlobalIdFieldResolver<T>(
classRef: Type<T>,
idFieldOptions?: GlobalIdFieldOptions,
): Type<GlobalIdFieldResolver> {
const globalIdFieldOptions = idFieldOptions || {};
@Resolver(classRef, { isAbstract: true })
abstract class GlobalIdFieldResolverHost {
@GlobalIdField(globalIdFieldOptions)
id(@Parent() parent: ResolverParent, @Info() info: ResolverInfo): ResolvedGlobalId {
if (!parent || !parent.id) {
throw new Error(`Cannot resolve id when 'parent' or 'parent.id' is null`);
}
switch (typeof parent.id) {
case 'object':
return parent.id;
case 'string':
return new ResolvedGlobalId({
type: info.parentType.name,
id: parent.id,
});
case 'number':
return new ResolvedGlobalId({
type: info.parentType.name,
id: parent.id.toString(),
});
}
}
}
return GlobalIdFieldResolverHost as Type<GlobalIdFieldResolver>;
}
Example #28
Source File: tag.resolver.ts From whispr with MIT License | 5 votes |
@Resolver(() => Tag)
export class TagResolver {
constructor(private readonly tagService: TagService, private readonly tagGroupService: TagGroupService) {}
/**
* Queries
*/
@Query(() => [Tag], { nullable: true })
async tags(@Args('tag') tagFilter: TagInputType): Promise<ITag[]> {
return this.tagService.findAll(tagFilter);
}
@Query(() => Tag, { nullable: true })
async tagById(@Args('id') id: string): Promise<ITag> {
return this.tagService.findOne(id);
}
/**
* Mutations
*/
@Mutation(() => Tag)
async createTag(@Args('tag') tag: TagInputType): Promise<ITag> {
return this.tagService.create(tag);
}
@Mutation(() => Tag)
async updateTag(@Args('id') id: string, @Args('tag') tag: TagInputType): Promise<ITag> {
return this.tagService.update(id, tag);
}
@Mutation(() => Tag)
async replaceTag(@Args('id') id: string, @Args('tag') tag: TagInputType): Promise<ITag> {
return this.tagService.replace(id, tag);
}
@Mutation(() => Boolean)
async deleteTag(@Args('id') id: string): Promise<boolean> {
return this.tagService.delete(id);
}
/**
* Field resolver
*/
@ResolveField()
async tagGroup(@Root() tag: Tag): Promise<ITagGroup> {
// eslint-disable-next-line no-underscore-dangle
return this.tagGroupService.findOne(tag.tagGroup._id);
}
}
Example #29
Source File: form.field.resolver.ts From api with GNU Affero General Public License v3.0 | 5 votes |
@Resolver(FormFieldModel)
export class FormFieldResolver {
constructor(
private readonly idService: IdService,
) {
}
@ResolveField(() => [FormFieldOptionModel])
async options(
@Parent() parent: FormFieldModel,
@Context('cache') cache: ContextCache,
): Promise<FormFieldOptionModel[]> {
const field = await cache.get<FormFieldEntity>(cache.getCacheKey(
FormFieldEntity.name,
parent._id
))
if (!field.options) {
return []
}
return field.options.map(option => new FormFieldOptionModel(
this.idService.encode(option.id),
option,
))
}
@ResolveField(() => [FormFieldLogicModel])
async logic(
@Parent() parent: FormFieldModel,
@Context('cache') cache: ContextCache,
): Promise<FormFieldLogicModel[]> {
const field = await cache.get<FormFieldEntity>(cache.getCacheKey(
FormFieldEntity.name,
parent._id
))
if (!field.logic) {
return []
}
return field.logic.map(logic => new FormFieldLogicModel(
this.idService.encode(logic.id),
logic,
))
}
@ResolveField(() => FormFieldRatingModel, { nullable: true })
async rating(
@Parent() parent: FormFieldModel,
@Context('cache') cache: ContextCache,
): Promise<FormFieldRatingModel> {
const field = await cache.get<FormFieldEntity>(cache.getCacheKey(
FormFieldEntity.name,
parent._id
))
if (!field.rating) {
return null
}
return new FormFieldRatingModel(field.rating)
}
}