/
index.html
106 lines (95 loc) · 3.56 KB
/
index.html
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
100
101
102
103
104
105
106
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Course Tracker Review Subscription</title>
<script type="text/javascript" src="https://unpkg.com/graphql-ws/umd/graphql-ws.min.js"></script>
<script>
class Graphql {
constructor(url) {
this.client = graphqlWs.createClient({url: url})
}
subscribe(query, callback) {
this.client.subscribe(
{query: query},
{
next: callback,
error: (err) => console.error('Error occurred', err),
complete: () => console.log('Subscription completed'),
},
);
}
async query(queryString) {
return await new Promise((resolve, reject) => {
let result;
this.client.subscribe(
{
query: queryString
},
{
next: (data) => (result = data),
error: reject,
complete: () => resolve(result)
}
);
})
}
}
class CourseReviewSubscription {
constructor() {
this.client = new Graphql('ws://localhost:8080/graphql')
}
async getCourses() {
const q = `{ courses { id, name } }`
return (await this.client.query(q)) ['data']['courses']
}
async addCourse(name, category, description) {
const q =
`mutation {
addCourse(name: "${name}", category: "${category}", description: "${description}") {
name
}
}`
return (await this.client.query(q)) ['data']['addCourse']
}
async addReview(courseId, reviewerName, rating, comment) {
const q =
`mutation {
addReview(courseId: ${courseId}, reviewerName: "${reviewerName}", rating: ${rating}, comment: "${comment}") {
id,
reviewerName,
comment,
rating
}
}`
return (await this.client.query(q)) ['data']['addReview']
}
subscribeToCourseReviews(courseId, callback) {
const q = `
subscription {
reviewEvents(courseId: ${courseId}) {
id,
reviewerName,
comment,
rating
}
}
`
this.client.subscribe(q, (next) => {
const result = next ['data']['reviewEvents']
callback(result)
});
}
}
window.addEventListener('load', async () => {
const crs = new CourseReviewSubscription();
await crs.addReview(1, 'Leena', 5, 'A 5-star course')
await crs.subscribeToCourseReviews(1, (event) => {
console.log(JSON.stringify({reviewId: event.id, reviewerName: event.reviewerName, comment: event.comment, rating: event.rating}));
})
});
</script>
</head>
<body>
</body>
</html>