Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions src/routes/graphql/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import { createGqlResponseSchema, gqlResponseSchema } from './schemas.js';
import { graphql } from 'graphql';
import { graphql, validate, specifiedRules, parse, GraphQLSchema } from 'graphql';
import { RootQueryType } from './resolvers/queries.js';
import { Mutations } from './resolvers/mutations.js';
import depthLimit from 'graphql-depth-limit';
import { createLoaders } from './loaders.js';

const schema = new GraphQLSchema({
query: RootQueryType,
mutation: Mutations,
});

const plugin: FastifyPluginAsyncTypebox = async (fastify) => {
const { prisma } = fastify;
Expand All @@ -15,7 +24,31 @@ const plugin: FastifyPluginAsyncTypebox = async (fastify) => {
},
},
async handler(req) {
// return graphql();
const document = parse(req.body.query);
const validationErrors = validate(schema, document, [
...specifiedRules,
depthLimit(5),
]);

if (validationErrors.length > 0) {
return {
errors: validationErrors,
};
}

const loaders = createLoaders(prisma);

const result = await graphql({
schema,
source: req.body.query,
variableValues: req.body.variables,
rootValue: {},
contextValue: { prisma, loaders },
fieldResolver: undefined,
typeResolver: undefined,
});

return result;
},
});
};
Expand Down
106 changes: 106 additions & 0 deletions src/routes/graphql/loaders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import DataLoader from 'dataloader';
import type { PrismaClient } from '@prisma/client';

export const createLoaders = (prisma: PrismaClient) => {
const userLoader = new DataLoader<
string,
Awaited<ReturnType<typeof prisma.user.findUnique>>
>(async (ids) => {
const users = await prisma.user.findMany({
where: {
id: { in: Array.from(ids) },
},
});
const userMap = new Map(users.map((user) => [user.id, user]));
return ids.map((id) => userMap.get(id) ?? null);
});

const postLoader = new DataLoader<
string,
Awaited<ReturnType<typeof prisma.post.findMany>>
>(async (authorIds) => {
const posts = await prisma.post.findMany({
where: {
authorId: { in: Array.from(authorIds) },
},
});
const postsByAuthor = new Map<string, typeof posts>();
for (const post of posts) {
const existing = postsByAuthor.get(post.authorId) ?? [];
existing.push(post);
postsByAuthor.set(post.authorId, existing);
}
return authorIds.map((authorId) => postsByAuthor.get(authorId) ?? []);
});

const profileLoader = new DataLoader<
string,
Awaited<ReturnType<typeof prisma.profile.findUnique>>
>(async (userIds) => {
const profiles = await prisma.profile.findMany({
where: {
userId: { in: Array.from(userIds) },
},
});
const profileMap = new Map(profiles.map((profile) => [profile.userId, profile]));
return userIds.map((userId) => profileMap.get(userId) ?? null);
});

const memberTypeLoader = new DataLoader<
string,
Awaited<ReturnType<typeof prisma.memberType.findUnique>>
>(async (ids) => {
const memberTypes = await prisma.memberType.findMany({
where: {
id: { in: Array.from(ids) },
},
});
const memberTypeMap = new Map(
memberTypes.map((memberType) => [memberType.id, memberType]),
);
return ids.map((id) => memberTypeMap.get(id) ?? null);
});

const userSubscribedToLoader = new DataLoader<string, string[]>(async (userIds) => {
const subscriptions = await prisma.subscribersOnAuthors.findMany({
where: {
subscriberId: { in: Array.from(userIds) },
},
select: { subscriberId: true, authorId: true },
});
const subscriptionsByUser = new Map<string, string[]>();
for (const sub of subscriptions) {
const existing = subscriptionsByUser.get(sub.subscriberId) ?? [];
existing.push(sub.authorId);
subscriptionsByUser.set(sub.subscriberId, existing);
}
return userIds.map((userId) => subscriptionsByUser.get(userId) ?? []);
});

const subscribedToUserLoader = new DataLoader<string, string[]>(async (userIds) => {
const subscriptions = await prisma.subscribersOnAuthors.findMany({
where: {
authorId: { in: Array.from(userIds) },
},
select: { authorId: true, subscriberId: true },
});
const subscriptionsByUser = new Map<string, string[]>();
for (const sub of subscriptions) {
const existing = subscriptionsByUser.get(sub.authorId) ?? [];
existing.push(sub.subscriberId);
subscriptionsByUser.set(sub.authorId, existing);
}
return userIds.map((userId) => subscriptionsByUser.get(userId) ?? []);
});

return {
userLoader,
postLoader,
profileLoader,
memberTypeLoader,
userSubscribedToLoader,
subscribedToUserLoader,
};
};

export type Loaders = ReturnType<typeof createLoaders>;
240 changes: 240 additions & 0 deletions src/routes/graphql/resolvers/mutations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
import type { Loaders } from '../loaders.js';

import { GraphQLObjectType, GraphQLString, GraphQLNonNull } from 'graphql';
import { UUIDType } from '../types/uuid.js';
import { Post, CreatePostInput, ChangePostInput } from '../types/post.js';
import { Profile, CreateProfileInput, ChangeProfileInput } from '../types/profile.js';
import { User, CreateUserInput, ChangeUserInput } from '../types/user.js';
import { PrismaClient } from '@prisma/client';

interface Context {
prisma: PrismaClient;
loaders: Loaders;
}

export const Mutations = new GraphQLObjectType({
name: 'Mutations',
fields: () => ({
createUser: {
type: new GraphQLNonNull(User),
args: {
dto: {
type: new GraphQLNonNull(CreateUserInput),
},
},
resolve: (
_: unknown,
{ dto }: { dto: { name: string; balance: number } },
{ prisma }: Context,
) => {
return prisma.user.create({
data: dto,
});
},
},
createProfile: {
type: new GraphQLNonNull(Profile),
args: {
dto: {
type: new GraphQLNonNull(CreateProfileInput),
},
},
resolve: (
_: unknown,
{
dto,
}: {
dto: {
isMale: boolean;
yearOfBirth: number;
userId: string;
memberTypeId: string;
};
},
{ prisma }: Context,
) => {
return prisma.profile.create({
data: dto,
});
},
},
createPost: {
type: new GraphQLNonNull(Post),
args: {
dto: {
type: new GraphQLNonNull(CreatePostInput),
},
},
resolve: (
_: unknown,
{ dto }: { dto: { title: string; content: string; authorId: string } },
{ prisma }: Context,
) => {
return prisma.post.create({
data: dto,
});
},
},
changePost: {
type: new GraphQLNonNull(Post),
args: {
id: {
type: new GraphQLNonNull(UUIDType),
},
dto: {
type: new GraphQLNonNull(ChangePostInput),
},
},
resolve: (
_: unknown,
{ id, dto }: { id: string; dto: { title?: string; content?: string } },
{ prisma }: Context,
) => {
return prisma.post.update({
where: { id },
data: dto,
});
},
},
changeProfile: {
type: new GraphQLNonNull(Profile),
args: {
id: {
type: new GraphQLNonNull(UUIDType),
},
dto: {
type: new GraphQLNonNull(ChangeProfileInput),
},
},
resolve: (
_: unknown,
{
id,
dto,
}: {
id: string;
dto: { isMale?: boolean; yearOfBirth?: number; memberTypeId?: string };
},
{ prisma }: Context,
) => {
return prisma.profile.update({
where: { id },
data: dto,
});
},
},
changeUser: {
type: new GraphQLNonNull(User),
args: {
id: {
type: new GraphQLNonNull(UUIDType),
},
dto: {
type: new GraphQLNonNull(ChangeUserInput),
},
},
resolve: (
_: unknown,
{ id, dto }: { id: string; dto: { name?: string; balance?: number } },
{ prisma }: Context,
) => {
return prisma.user.update({
where: { id },
data: dto,
});
},
},
deleteUser: {
type: new GraphQLNonNull(GraphQLString),
args: {
id: {
type: new GraphQLNonNull(UUIDType),
},
},
resolve: async (_: unknown, { id }: { id: string }, { prisma }: Context) => {
await prisma.user.delete({
where: { id },
});
return id;
},
},
deletePost: {
type: new GraphQLNonNull(GraphQLString),
args: {
id: {
type: new GraphQLNonNull(UUIDType),
},
},
resolve: async (_: unknown, { id }: { id: string }, { prisma }: Context) => {
await prisma.post.delete({
where: { id },
});
return id;
},
},
deleteProfile: {
type: new GraphQLNonNull(GraphQLString),
args: {
id: {
type: new GraphQLNonNull(UUIDType),
},
},
resolve: async (_: unknown, { id }: { id: string }, { prisma }: Context) => {
await prisma.profile.delete({
where: { id },
});
return id;
},
},
subscribeTo: {
type: new GraphQLNonNull(GraphQLString),
args: {
userId: {
type: new GraphQLNonNull(UUIDType),
},
authorId: {
type: new GraphQLNonNull(UUIDType),
},
},
resolve: async (
_: unknown,
{ userId, authorId }: { userId: string; authorId: string },
{ prisma }: Context,
) => {
await prisma.subscribersOnAuthors.create({
data: {
subscriberId: userId,
authorId,
},
});
return userId;
},
},
unsubscribeFrom: {
type: new GraphQLNonNull(GraphQLString),
args: {
userId: {
type: new GraphQLNonNull(UUIDType),
},
authorId: {
type: new GraphQLNonNull(UUIDType),
},
},
resolve: async (
_: unknown,
{ userId, authorId }: { userId: string; authorId: string },
{ prisma }: Context,
) => {
await prisma.subscribersOnAuthors.delete({
where: {
subscriberId_authorId: {
subscriberId: userId,
authorId,
},
},
});
return userId;
},
},
}),
});
Loading