-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
106 lines (92 loc) · 2.73 KB
/
index.js
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
import { ApolloServer, gql } from 'apollo-server';
import dotenv from "dotenv-override";
import { makeExecutableSchema } from "graphql-tools";
import { IsAuthenticatedDirective, HasRoleDirective, HasScopeDirective } from "graphql-auth-user-directives";
dotenv.config({override: true});
// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = gql`
directive @hasScope(scopes: [String]) on OBJECT | FIELD_DEFINITION
directive @hasRole(roles: [Role]) on OBJECT | FIELD_DEFINITION
directive @isAuthenticated on OBJECT | FIELD_DEFINITION
enum Role {
visitor
admin
}
# This "Book" type defines the queryable fields for every book in our data source.
type Book {
title: String,
addedBy: String
}
type Author {
name: String,
}
# The "Query" type is special: it lists all of the available queries that
# clients can execute, along with the return type for each. In this
# case, the "books" query returns an array of zero or more Books (defined above).
type Query {
books: [Book] @hasScope(scopes: ["books:view"])
authors: [Author] @hasScope(scopes: ["authors:view"])
}
type Mutation {
addBook(title: String): Book @hasScope(scopes: ["book:create"])
}
`;
let books = [
{
title: 'Harry Potter and the Chamber of Secrets',
addedBy: 'Peter'
},
{
title: 'Jurassic Park',
addedBy: 'Nathan'
},
];
let authors = [
{
name: 'J.K. Rowling'
},
{
name: 'Michael Crichton',
},
];
// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
Query: {
books: () => books,
authors: () => authors,
},
Mutation: {
addBook: (object, params, ctx, resolveInfo) => {
const newBook = {
title: params.title,
addedBy: ctx.user.name
};
books.push(newBook);
return newBook;
}
}
};
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const schema = makeExecutableSchema({
typeDefs,
resolvers,
schemaDirectives: {
isAuthenticated: IsAuthenticatedDirective,
hasRole: HasRoleDirective,
hasScope: HasScopeDirective
}
});
const server = new ApolloServer({
schema,
context: ({ req }) => {
return req;
}
});
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});