feat: enhance createSport functionality with conflict handling and result management
Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
@@ -1,18 +1,10 @@
|
||||
import { Prisma } from '@/generated/prisma/client';
|
||||
import { handleResult } from '@/lib/http/handle-result';
|
||||
import { createSport } from '@/modules/sport/services/sport.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { CreateSportInput } from '@repo/api-contract';
|
||||
|
||||
export async function createSportHandler(c: AppContext) {
|
||||
const payload = c.req.valid('json' as never) as CreateSportInput;
|
||||
|
||||
try {
|
||||
const sport = await createSport(payload);
|
||||
return c.json(sport, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
return c.json({ message: 'No se pudo crear el deporte.' }, 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return handleResult(c, await createSport(payload), 201);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Prisma, Sport } from '@/generated/prisma/client';
|
||||
import { Errors } from '@/lib/errors';
|
||||
import { db } from '@/lib/prisma';
|
||||
import { ok, Result } from '@/lib/result';
|
||||
import { err, ok, Result } from '@/lib/result';
|
||||
import { v7 as uuidv7 } from 'uuid';
|
||||
|
||||
export type CreateSportInput = {
|
||||
@@ -62,7 +63,15 @@ export async function listSports(): Promise<Result<Sport[]>> {
|
||||
export async function createSport(input: CreateSportInput) {
|
||||
const slug = await buildUniqueSlug(input.name);
|
||||
|
||||
return db.sport.create({
|
||||
const existing = await db.sport.count({
|
||||
where: { slug },
|
||||
});
|
||||
|
||||
if (existing > 0) {
|
||||
return err(Errors.conflict('Ya existe un deporte con ese nombre.'));
|
||||
}
|
||||
|
||||
var created = db.sport.create({
|
||||
data: {
|
||||
id: uuidv7(),
|
||||
name: input.name.trim(),
|
||||
@@ -70,6 +79,8 @@ export async function createSport(input: CreateSportInput) {
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
return ok(created);
|
||||
}
|
||||
|
||||
export async function getSportById(id: string) {
|
||||
|
||||
Reference in New Issue
Block a user