import { Ability, ForbiddenError } from "@casl/ability"; import { PrismaClient, User, UserCreateInput } from '@prisma/client'; import { ValidationError } from "apollo-server-micro"; // import { database as db } from '../../database'; interface serviceContext { ability: Ability }; export const userService = (db: PrismaClient) => ({ /** * Find a user with a given Id */ async fetchUserById(id: User['id'], ctx: serviceContext) { const user = await db.user.findOne({ where: { id } }); if (!!user) { ForbiddenError.from(ctx.ability).throwUnlessCan('read', user); } return user; }, /** * Register a new user */ async registerUser(data: UserCreateInput, ctx: serviceContext) { const { email } = data; ForbiddenError.from(ctx.ability).throwUnlessCan('create', data); const existingUser = await db.user.findOne({ where: { email } }); if (existingUser) { throw new ValidationError('Email is already associated with an account'); } return db.user.create({ data }); } });