add context subscription

This commit is contained in:
2024-10-29 02:21:18 +07:00
parent ba54d3466c
commit 9423a36eeb
7 changed files with 58 additions and 19 deletions

View File

@@ -138,8 +138,11 @@ export class CenterMentorSchema extends PothosSchema {
}, },
resolve: async (query, root, args, ctx) => { resolve: async (query, root, args, ctx) => {
return this.prisma.$transaction(async (prisma) => { return this.prisma.$transaction(async (prisma) => {
if (ctx.isSubscription) {
throw new Error('Not allowed');
}
// get centerId by user id from context // get centerId by user id from context
const userId = ctx.me.id; const userId = ctx.http.me.id;
if (!userId) { if (!userId) {
throw new Error('User ID is required'); throw new Error('User ID is required');
} }
@@ -213,6 +216,9 @@ export class CenterMentorSchema extends PothosSchema {
adminNote: t.arg({ type: 'String', required: false }), adminNote: t.arg({ type: 'String', required: false }),
}, },
resolve: async (query, root, args, ctx, info) => { resolve: async (query, root, args, ctx, info) => {
if (ctx.isSubscription) {
throw new Error('Not allowed');
}
return this.prisma.$transaction(async (prisma) => { return this.prisma.$transaction(async (prisma) => {
// validate input // validate input
if (args.approved && !args.adminNote) { if (args.approved && !args.adminNote) {
@@ -264,7 +270,7 @@ export class CenterMentorSchema extends PothosSchema {
data: { data: {
content: args.adminNote ?? '', content: args.adminNote ?? '',
mentorId: mentor.id, mentorId: mentor.id,
notedByUserId: ctx.me.id, notedByUserId: ctx.http.me.id,
}, },
}); });
// update user role // update user role
@@ -310,7 +316,7 @@ export class CenterMentorSchema extends PothosSchema {
adminNote: { adminNote: {
create: { create: {
content: args.adminNote ?? '', content: args.adminNote ?? '',
notedByUserId: ctx.me.id, notedByUserId: ctx.http.me.id,
updatedAt: new Date(), updatedAt: new Date(),
}, },
}, },

View File

@@ -25,13 +25,25 @@ import { getDatamodel } from '../types/pothos.generated';
// import { rules } from '../common/graphql/common.graphql.auth-rule'; // import { rules } from '../common/graphql/common.graphql.auth-rule';
export interface SchemaContext { export type SchemaContext =
req: Request; | {
res: Response; isSubscription: true;
me: User; websocket: {
pubSub: PubSub; pubSub: PubSub;
generator: PrismaCrudGenerator<BuilderTypes>; me: User;
} generator: PrismaCrudGenerator<BuilderTypes>;
};
}
| {
isSubscription: false;
http: {
req: Request;
res: Response;
me: User;
pubSub: PubSub;
generator: PrismaCrudGenerator<BuilderTypes>;
};
};
// extend prisma types to contain string type // extend prisma types to contain string type
export interface SchemaBuilderOption { export interface SchemaBuilderOption {
@@ -79,8 +91,11 @@ export class Builder extends SchemaBuilder<SchemaBuilderOption> {
], ],
smartSubscriptions: { smartSubscriptions: {
debounceDelay: 1000, debounceDelay: 1000,
...subscribeOptionsFromIterator((name, { pubSub }) => { ...subscribeOptionsFromIterator((name, ctx) => {
return pubSub.asyncIterator(name); if (ctx.isSubscription) {
return ctx.websocket.pubSub.asyncIterator(name);
}
return ctx.http.pubSub.asyncIterator(name);
}), }),
}, },
relay: {}, relay: {},

View File

@@ -93,7 +93,10 @@ import { initContextCache } from '@pothos/core';
}, },
context: async ({ req }: { req: Request }) => ({ context: async ({ req }: { req: Request }) => ({
...initContextCache(), ...initContextCache(),
me: await graphqlService.acquireContext(req), isSubscription: false,
http: {
me: await graphqlService.acquireContext(req),
},
}), }),
}), }),
}), }),

View File

@@ -109,7 +109,10 @@ export class MessageSchema extends PothosSchema {
...query, ...query,
data: args.input, data: args.input,
}); });
ctx.pubSub.publish('MESSAGE_SENT', message); if (ctx.isSubscription) {
throw new Error('Not allowed');
}
ctx.http.pubSub.publish('MESSAGE_SENT', message);
return message; return message;
}, },
}), }),
@@ -124,9 +127,12 @@ export class MessageSchema extends PothosSchema {
this.builder.subscriptionFields((t) => ({ this.builder.subscriptionFields((t) => ({
messageSent: t.field({ messageSent: t.field({
subscribe: (_, __, ctx) => { subscribe: (_, __, ctx) => {
if (!ctx.isSubscription) {
throw new Error('Not allowed');
}
return { return {
[Symbol.asyncIterator]: () => [Symbol.asyncIterator]: () =>
ctx.pubSub.asyncIterator('MESSAGE_SENT'), ctx.websocket.pubSub.asyncIterator('MESSAGE_SENT'),
}; };
}, },
type: this.message(), // Add the type property type: this.message(), // Add the type property

View File

@@ -108,10 +108,13 @@ export class ResumeSchema extends PothosSchema {
}, },
resolve: async (query, root, args, ctx, info) => { resolve: async (query, root, args, ctx, info) => {
try { try {
if (ctx.isSubscription) {
throw new Error('Not allowed');
}
const resumes = await this.prisma.resume.findMany({ const resumes = await this.prisma.resume.findMany({
...query, ...query,
where: { where: {
userId: ctx.me.id, userId: ctx.http.me.id,
status: args.status ?? undefined, status: args.status ?? undefined,
}, },
}); });

View File

@@ -243,6 +243,9 @@ export class ServiceSchema extends PothosSchema {
}), }),
}, },
resolve: async (query, root, args, ctx, info) => { resolve: async (query, root, args, ctx, info) => {
if (ctx.isSubscription) {
throw new Error('Not allowed');
}
return await this.prisma.$transaction(async (prisma) => { return await this.prisma.$transaction(async (prisma) => {
// check if service is already approved or rejected // check if service is already approved or rejected
const service = await prisma.service.findUnique({ const service = await prisma.service.findUnique({
@@ -265,7 +268,7 @@ export class ServiceSchema extends PothosSchema {
adminNote: { adminNote: {
create: { create: {
content: args.adminNote ?? '', content: args.adminNote ?? '',
notedByUserId: ctx.me.id, notedByUserId: ctx.http.me.id,
}, },
}, },
}, },

View File

@@ -127,10 +127,13 @@ export class UserSchema extends PothosSchema {
}, },
}), }),
me: t.prismaField({ me: t.prismaField({
description: 'Retrieve the current user by token.', description: 'Retrieve the current user in context.',
type: this.user(), type: this.user(),
resolve: async (query, root, args, ctx) => { resolve: async (query, root, args, ctx) => {
return ctx.me; if (ctx.isSubscription) {
throw new Error('Not allowed');
}
return ctx.http.me;
}, },
}), }),