-
Notifications
You must be signed in to change notification settings - Fork 114
/
index.ts
84 lines (74 loc) · 2.12 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
import "reflect-metadata";
import path from "path";
import { PrismaClient } from "@prisma/client";
import { Resolver, Query, FieldResolver, Ctx, Root } from "type-graphql";
import { TypeGraphQLModule } from "typegraphql-nestjs";
import { NestFactory } from "@nestjs/core";
import { Module } from "@nestjs/common";
import { ApolloDriver } from "@nestjs/apollo";
import {
NestExpressApplication,
ExpressAdapter,
} from "@nestjs/platform-express";
import {
User,
Post,
UserRelationsResolver,
PostRelationsResolver,
UserCrudResolver,
PostCrudResolver,
} from "./prisma/generated/type-graphql";
interface Context {
prisma: PrismaClient;
}
// custom resolver for custom business logic using Prisma Client
@Resolver(of => User)
class CustomUserResolver {
@Query(returns => User, { nullable: true })
async bestUser(@Ctx() { prisma }: Context): Promise<User | null> {
return await prisma.user.findFirst({
where: { email: "[email protected]" },
});
}
@FieldResolver(type => Post, { nullable: true })
async favoritePost(
@Root() user: User,
@Ctx() { prisma }: Context,
): Promise<Post | undefined> {
const [favoritePost] = await prisma.user
.findUniqueOrThrow({ where: { id: user.id } })
.posts({ take: 1 });
return favoritePost;
}
}
async function main() {
const prisma = new PrismaClient();
@Module({
imports: [
// use the TypeGraphQLModule to expose Prisma by GraphQL
TypeGraphQLModule.forRoot({
driver: ApolloDriver,
path: "/",
emitSchemaFile: path.resolve(__dirname, "./generated-schema.graphql"),
validate: false,
context: (): Context => ({ prisma }),
}),
],
providers: [
// register all resolvers inside `providers` of the Nest module
CustomUserResolver,
UserRelationsResolver,
UserCrudResolver,
PostRelationsResolver,
PostCrudResolver,
],
})
class AppModule {}
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
new ExpressAdapter(),
);
await app.listen(4000);
console.log(`GraphQL is listening on 4000!`);
}
main().catch(console.error);