-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathindex.ts
129 lines (109 loc) · 2.44 KB
/
index.ts
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import * as express from 'express';
import { Entity, BaseEntity, ManyToOne, OneToMany } from 'typeorm';
import {
Schema,
Query,
Mutation,
ObjectType,
Field,
compileSchema,
} from 'typegql';
import * as graphqlHTTP from 'express-graphql';
import { PrimaryGeneratedColumn, Column, createConnection } from 'typeorm';
@Entity()
@ObjectType()
export class Book extends BaseEntity {
@PrimaryGeneratedColumn()
@Field()
id: number;
@Column()
@Field()
title: string;
@Column()
@Field()
pagesCount: number;
@ManyToOne(type => User, user => user.books, { lazy: true })
@Field({ type: () => User })
author: User;
}
@Entity()
@ObjectType()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
@Field()
id: number;
@Column()
@Field()
name: string;
@Column()
@Field()
age: number;
@OneToMany(type => Book, book => book.author)
@Field({ type: () => [Book] })
books: Book[];
@Field()
isAdult(): boolean {
return this.age > 21;
}
}
@Schema()
class ApiSchema {
@Query({ type: [User] })
async getAllUsers(): Promise<User[]> {
const allUsers = await User.find();
return allUsers;
}
@Query({ type: User })
async getUserByName(name: string): Promise<User> {
const user = await User.findOne({ where: { name } });
return user;
}
@Query({ type: [Book] })
async getAllBooks(): Promise<Book[]> {
const books = await Book.find();
return books;
}
@Mutation({ type: User })
async createUser(name: string, age: number): Promise<User> {
const newUser = User.create({ age, name });
return await newUser.save();
}
@Mutation({ type: Book })
async createBook(
title: string,
pagesCount: number,
authorId: number,
): Promise<Book> {
const newBook = Book.create({
title,
pagesCount,
author: { id: authorId },
});
return await newBook.save();
}
}
const compiledSchema = compileSchema(ApiSchema);
const app = express();
async function startApp() {
console.log('Connecting to database');
const connection = await createConnection({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'adam',
password: '',
database: 'test',
entities: [User, Book],
synchronize: true,
});
console.log('Connected');
app.use(
'/graphql',
graphqlHTTP({
schema: compiledSchema,
graphiql: true,
}),
);
app.listen(3000, () => console.log('API ready on port 3000'));
}
startApp();