forked from prismake/typegql
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
132 lines (112 loc) · 2.32 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
130
131
132
import express from 'express'
import {
SchemaRoot,
Query,
Mutation,
ObjectType,
Field,
compileSchema
} from '../../src/index.js'
import graphqlHTTP from 'express-graphql'
import {
PrimaryGeneratedColumn,
Column,
createConnection,
Entity,
BaseEntity,
ManyToOne,
OneToMany
} from 'typeorm'
@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
}
}
@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
}
@SchemaRoot()
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 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 newBook.save()
}
}
const compiledSchema = compileSchema(ApiSchema)
const app = express()
async function startApp() {
console.log('Connecting to database')
const connection = await createConnection({
type: 'sqlite',
database: 'test',
entities: [User, Book],
synchronize: true
})
console.log('Connected')
app.use(
'/graphql',
graphqlHTTP({
schema: compiledSchema,
graphiql: true
})
)
app.listen(5000, () => console.log('API ready on port 3000'))
}
startApp()