authors.resolver.ts
2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import {
Args,
Mutation,
Query,
Resolver,
Subscription,
ResolveField,
Parent,
Int,
} from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';
import { Author } from './models/author.model';
import { Post } from './models/post.model';
import { AuthorsService } from './authors.service';
import { PostsService } from './posts.service';
const pubSub = new PubSub();
@Resolver(() => Author)
export class AuthorsResolver {
constructor(
private authorsService: AuthorsService,
private postsService: PostsService,
) {}
@Query((returns) => Author)
async author(@Args('id', { type: () => Int }) id: number) {
return this.authorsService.findOneById(id);
}
// 根据id查询作者信息
@Query((returns) => Author, {
name: 'author',
description: 'get author info by id',
nullable: false,
})
async getAuthor(
@Args('id', {
type: () => Int,
description: 'author id',
nullable: false,
})
id: number,
): Promise<any> {
return {
id,
firstName: 'wu',
lastName: 'pat',
};
}
// 修改作者信息
@Mutation((returns) => Author, {
name: 'changeAuthor',
description: 'change author info by id',
nullable: false,
})
async changeAuthor(
@Args('id') id: number,
@Args('firstName') firstName: string,
@Args('lastName') lastName: string,
): Promise<any> {
return {
id,
firstName,
lastName,
};
}
// 解析posts字段
@ResolveField()
async posts(@Parent() author: Author): Promise<any> {
const { id } = author;
return [
{
id: 4,
title: 'hello',
votes: 2112,
},
];
}
// 新增文章
@Mutation((returns) => Post)
async addPost() {
const newPost = {
id: 1,
title: '新增文章',
};
// 新增成功后,通知更新
await pubSub.publish('postAdded', { postAdded: newPost });
return newPost;
}
// 监听变更
@Subscription((returns) => Post, {
name: 'postAdded',
})
async postAdded(/*@Args('title') title: string*/) {
return pubSub.asyncIterator('postAdded');
}
}