import { schema } from 'nexus' import { send as sendNotifications } from '../../utils/notification' import GeneralUtils from '../../utils/general' import { logger } from '../../utils/logger' import * as Auth from '../../utils/auth' export const Contact = schema.objectType({ name: 'Contact', definition(t) { t.model.id() t.model.createdAt() t.model.updatedAt() t.model.firstName() t.model.lastName() t.model.fullname() t.model.title() t.model.email() t.model.isPrivate() t.model.website() t.model.avatar() t.model.phone() t.model.project() t.model.projects() t.model.seenBy() }, }) export const ContactMutation = schema.extendType({ type: 'Mutation', definition: (t) => { t.crud.deleteOneContact({ alias: 'deleteContact' }) t.crud.updateOneContact({ alias: 'updateContact' }) t.crud.createOneContact({ alias: 'createContact' }) t.field('createContact', { type: 'Contact', args: { where: schema.arg({ type: 'ContactWhereUniqueInput' }), data: schema.arg({ type: 'ContactCreateInput' }), }, resolve: async (parent, { data }, ctx: NexusContext) => { const createdContact = await ctx.prisma.contact.create({ data: { ...data }, select: { id: true, firstName: true, lastName: true, isPrivate: true, project: { select: { id: true, name: true, users: { select: { id: true, }, }, }, }, }, }) if (!createdContact.isPrivate) { // Send notification for the app try { await sendNotifications({ noEmail: true, noSMS: true, users: createdContact.project.users, title: 'New contact', projectId: createdContact.project.id, message: GeneralUtils.getUserName(createdContact), type: 'NEW_CONTACT', data: { id: createdContact.id, }, }) } catch (e) { logger.error(e) } } return ctx.prisma.contact.findOne({ where: { id: createdContact.id } }) }, }) }, }) export const ContactQueries = schema.extendType({ type: 'Query', definition(t) { t.crud.contact() t.field('contacts', { type: 'Contact', list: true, args: { where: schema.arg({ type: 'ContactWhereInput' }) }, resolve: async (_, args, ctx: NexusContext) => { const userId = Auth.getUserId(ctx) const [user, contacts] = await Promise.all([ ctx.prisma.user.findOne({ where: { id: userId }, select: { role: true } }), // WTF ? Can Thierry verify this ctx.prisma.contact.findMany({ where: { ...args.where } }), ]) if (user.role === 'RESIDENT') { return contacts.filter((contact) => !contact.isPrivate) } return contacts }, }) }, })