feat: implement createServiceFeedback mutation in ServiceFeedbackSchema

- Added a new mutation field `createServiceFeedback` to allow users to submit feedback for services.
- Implemented validation checks to ensure only authorized users (CUSTOMER role) can submit feedback for completed orders.
- Included error handling for invalid ratings and comment length, enhancing data integrity and user experience.
- Improved the overall structure and clarity of the ServiceFeedbackSchema by integrating the new mutation.
This commit is contained in:
2024-12-06 16:57:04 +07:00
parent db2b3e9dd4
commit 4931f382b3

View File

@@ -2,6 +2,7 @@ import { Inject, Injectable } from '@nestjs/common'
import { Pothos, PothosRef, PothosSchema, SchemaBuilderToken } from '@smatch-corp/nestjs-pothos' import { Pothos, PothosRef, PothosSchema, SchemaBuilderToken } from '@smatch-corp/nestjs-pothos'
import { Builder } from '../Graphql/graphql.builder' import { Builder } from '../Graphql/graphql.builder'
import { PrismaService } from '../Prisma/prisma.service' import { PrismaService } from '../Prisma/prisma.service'
import { OrderStatus, Role, ScheduleStatus } from '@prisma/client'
@Injectable() @Injectable()
export class ServiceFeedbackSchema extends PothosSchema { export class ServiceFeedbackSchema extends PothosSchema {
@@ -70,5 +71,60 @@ export class ServiceFeedbackSchema extends PothosSchema {
}, },
}), }),
})) }))
this.builder.mutationFields((t) => ({
createServiceFeedback: t.prismaField({
type: this.serviceFeedback(),
args: {
orderId: t.arg({
type: 'String',
required: true,
}),
rating: t.arg({
type: 'Float',
required: true,
}),
comments: t.arg({
type: 'String',
required: false,
}),
},
description: 'Create a new service feedback.',
resolve: async (_, _root, args, ctx, _info) => {
if (ctx.isSubscription) throw new Error('Not allowed')
if (!ctx.http?.me) throw new Error('Unauthorized')
// allow only when user is CUSTOMER and order is completed
if (ctx.http?.me?.role !== Role.CUSTOMER) throw new Error('Unauthorized')
const order = await this.prisma.order.findFirst({
where: {
id: args.orderId,
userId: ctx.http?.me?.id,
status: OrderStatus.PAID,
schedule: {
dates: {
every: {
status: ScheduleStatus.COMPLETED,
},
},
},
},
})
if (!order) throw new Error('Order not found')
if (order.userId !== ctx.http?.me?.id) throw new Error('Unauthorized')
if (order.status !== OrderStatus.PAID) throw new Error('Order not completed')
// validate rating
if (args.rating < 0 || args.rating > 5) throw new Error('Invalid rating')
// validate comments
if (args.comments && args.comments.length > 1024) throw new Error('Comments too long')
return await this.prisma.serviceFeedback.create({
data: {
userId: ctx.http?.me?.id,
serviceId: order.serviceId,
rating: args.rating,
comments: args.comments,
},
})
},
}),
}))
} }
} }