diff --git a/resolvers/editor.py b/resolvers/editor.py index 4a054e33..d8f8d713 100644 --- a/resolvers/editor.py +++ b/resolvers/editor.py @@ -113,17 +113,35 @@ async def create_shout(_, info, inp): inp["created_at"] = current_time inp["updated_at"] = current_time inp["created_by"] = author_dict.get("id") - inp["community"] = inp.get("community", 1) # Устанавливаем значение по умолчанию - inp["slug"] = inp.get("slug") or f"draft-{current_time}" # Генерируем slug если не указан - inp["lang"] = inp.get("lang", "ru") # Устанавливаем язык по умолчанию + inp["community"] = inp.get("community", 1) + + # Генерация уникального slug с ограничением длины + base_slug = inp.get("slug") or f"draft-{current_time}" + slug = base_slug + counter = 1 + max_attempts = 10 # Ограничиваем количество попыток + + while counter <= max_attempts: + existing_slug = session.query(Shout).filter(Shout.slug == slug).first() + if not existing_slug: + break + slug = f"{base_slug[:50]}-{counter}" # Ограничиваем длину базового slug + counter += 1 + + if counter > max_attempts: + # Если не удалось создать уникальный slug, используем timestamp + slug = f"draft-{current_time}-{author_dict.get('id')}" + + inp["slug"] = slug + inp["lang"] = inp.get("lang", "ru") # Добавляем обязательные поля контента - inp["title"] = inp.get("title", "Без названия") # Значение по умолчанию для заголовка - inp["body"] = inp.get("body", "") # Пустое тело по умолчанию + inp["title"] = inp.get("title", "Без названия") + inp["body"] = inp.get("body", "") new_shout = Shout(**inp) session.add(new_shout) - session.flush() # Получаем id до коммита + session.flush() # Check for duplicate slug logger.debug(f"Checking for existing slug: {new_shout.slug}") @@ -321,13 +339,24 @@ async def update_shout(_, info, shout_id: int, shout_input=None, publish=False): logger.info(f"shout#{shout_id} found") if slug != shout_by_id.slug: - same_slug_shout = session.query(Shout).filter(Shout.slug == slug).first() - c = 1 - while same_slug_shout is not None: - c += 1 - slug = f"{slug}-{c}" - same_slug_shout = session.query(Shout).filter(Shout.slug == slug).first() - shout_input["slug"] = slug + base_slug = slug[:50] # Ограничиваем длину базового slug + new_slug = base_slug + counter = 1 + max_attempts = 10 + + while counter <= max_attempts: + same_slug_shout = ( + session.query(Shout).filter(and_(Shout.slug == new_slug, Shout.id != shout_id)).first() + ) + if not same_slug_shout: + break + new_slug = f"{base_slug}-{counter}" + counter += 1 + + if counter > max_attempts: + new_slug = f"{base_slug}-{current_time}" + + shout_input["slug"] = new_slug logger.info(f"shout#{shout_id} slug patched") if filter(lambda x: x.id == author_id, [x for x in shout_by_id.authors]) or "editor" in roles: