\update: the slugify method
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import slugify from "slugify";
|
||||
import { Not } from "typeorm";
|
||||
|
||||
import { BlogMessage, CommonMessage } from "../../../common/enums/message.enum";
|
||||
@@ -106,12 +105,13 @@ export class BlogsService {
|
||||
const category = await this.findCategoryById(createBlogDto.categoryId);
|
||||
|
||||
const slug = this.generateSlug(createBlogDto.slug);
|
||||
console.log(slug);
|
||||
|
||||
const blog = this.blogsRepository.create({
|
||||
...createBlogDto,
|
||||
slug,
|
||||
author: { id: authorId },
|
||||
category,
|
||||
slug,
|
||||
});
|
||||
|
||||
await this.blogsRepository.save(blog);
|
||||
@@ -140,10 +140,13 @@ export class BlogsService {
|
||||
if (updateBlogDto.slug) {
|
||||
const existBlog = await this.blogsRepository.findOne({ where: { slug: updateBlogDto.slug, id: Not(id) } });
|
||||
if (existBlog) throw new BadRequestException(BlogMessage.BLOG_ALREADY_EXISTS);
|
||||
blog.slug = this.generateSlug(updateBlogDto.slug);
|
||||
}
|
||||
|
||||
await this.blogsRepository.save({ ...blog, ...updateBlogDto });
|
||||
await this.blogsRepository.save({
|
||||
...blog,
|
||||
...updateBlogDto,
|
||||
slug: this.generateSlug(updateBlogDto.slug ?? blog.slug),
|
||||
});
|
||||
|
||||
return {
|
||||
message: CommonMessage.UPDATE_SUCCESS,
|
||||
@@ -258,8 +261,16 @@ export class BlogsService {
|
||||
}
|
||||
|
||||
//*********************************** */
|
||||
private generateSlug(title: string): string {
|
||||
return slugify(title, { lower: true, strict: true });
|
||||
private generateSlug(slug: string): string {
|
||||
if (!slug) return "";
|
||||
|
||||
// Replace spaces and special characters with hyphens, preserve Farsi characters
|
||||
return slug
|
||||
.trim()
|
||||
.replace(/[&\\#,+()$~%.'":*?<>{}]/g, "") // Remove special characters
|
||||
.replace(/\s+/g, "-") // Replace spaces with hyphens
|
||||
.replace(/-+/g, "-") // Replace multiple hyphens with single hyphen
|
||||
.trim();
|
||||
}
|
||||
|
||||
//*********************************** */
|
||||
|
||||
Reference in New Issue
Block a user