import { makeSchema, objectType, stringArg, intArg, idArg, enumType, inputObjectType, arg, mutationField, queryField } from '@nexus/schema';
const UserRole = enumType({ name: 'UserRole', members: ['ADMIN', 'USER'] });
const UserInput = inputObjectType({ name: 'UserInput', definition(t) { t.string('name'); t.int('age'); t.field('role', { type: UserRole }); } });
const User = objectType({ name: 'User', definition(t) { t.int('id'); t.string('name'); t.int('age'); t.field('role', { type: UserRole }); } });
let users = []; let currentId = 1;
const getUserQuery = queryField('getUser', { type: User, args: { id: idArg() }, resolve: (parent, { id }) => { return users.find(user => user.id === id); } });
const getUsersQuery = queryField('getUsers', { type: [User], resolve: () => { return users; } });
const addUserMutation = mutationField('addUser', { type: User, args: { user: arg({ type: UserInput }) }, resolve: (parent, { user }) => { const newUser = { id: currentId++, name: user.name, age: user.age, role: user.role }; users.push(newUser); return newUser; } });
const updateUserMutation = mutationField('updateUser', { type: User, args: { id: idArg(), user: arg({ type: UserInput }) }, resolve: (parent, { id, user }) => { const index = users.findIndex(u => u.id === id); if (index!== -1) { users[index] = {...users[index],...user }; return users[index]; } throw new Error('User not found'); } });
const deleteUserMutation = mutationField('deleteUser', { type: User, args: { id: idArg() }, resolve: (parent, { id }) => { const index = users.findIndex(u => u.id === id); if (index!== -1) { const removedUser = users[index]; users.splice(index, 1); return removedUser; } throw new Error('User not found'); } });
const schema = makeSchema({ types: [User, UserInput, UserRole, getUserQuery, getUsersQuery, addUserMutation, updateUserMutation, deleteUserMutation], outputs: { schema: __dirname + '/schema.graphql', typegen: __dirname + '/generated/nexus.ts' } });
export default schema;
|