basic structure setup

This commit is contained in:
dimitar committed 2026-01-10 19:41:04 +01:00
commit 71dfd86187
89 files changed
+41490

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
+12
View File
@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
+28
View File
@@ -0,0 +1,28 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ArticlesModule } from './modules/articles.module';
import { StrapiModule } from './modules/strapi.module';
import { Article, Author, Category } from './modules/entities';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
TypeOrmModule.forRoot({
type: 'sqlite',
database: process.env.DATABASE_PATH ?? './database.sqlite',
entities: [Article, Author, Category],
synchronize: process.env.NODE_ENV !== 'production',
logging: process.env.NODE_ENV === 'development',
}),
ArticlesModule,
StrapiModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
+20
View File
@@ -0,0 +1,20 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const allowedOrigins = [
process.env.FRONTEND_URL ?? 'http://localhost:5173',
process.env.STRAPI_URL ?? 'http://localhost:1337',
];
app.enableCors({
origin: allowedOrigins,
credentials: true,
});
app.setGlobalPrefix('api/v1');
await app.listen(process.env.PORT ?? 3000);
}
void bootstrap();
@@ -0,0 +1,57 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
ValidationPipe,
} from '@nestjs/common';
import { ArticlesService } from './articles.service';
import {
CreateArticleDto,
UpdateArticleDto,
FindArticlesDto,
} from './articles.dto';
@Controller('articles')
export class ArticlesController {
constructor(private readonly articlesService: ArticlesService) {}
@Post()
create(@Body(new ValidationPipe({ transform: true })) dto: CreateArticleDto) {
return this.articlesService.create(dto);
}
@Get()
findAll(
@Query(new ValidationPipe({ transform: true })) dto: FindArticlesDto,
) {
return this.articlesService.findAll(dto);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.articlesService.findOne(id);
}
@Get('slug/:slug')
findBySlug(@Param('slug') slug: string) {
return this.articlesService.findBySlug(slug);
}
@Put(':id')
update(
@Param('id') id: string,
@Body(new ValidationPipe({ transform: true })) dto: UpdateArticleDto,
) {
return this.articlesService.update(id, dto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.articlesService.remove(id);
}
}
+123
View File
@@ -0,0 +1,123 @@
import {
IsString,
IsOptional,
IsEnum,
IsArray,
IsUUID,
IsNumber,
} from 'class-validator';
import { ArticleStatus } from './entities';
export class CreateArticleDto {
@IsString()
title: string;
@IsString()
content: string;
@IsOptional()
@IsString()
excerpt?: string;
@IsOptional()
@IsString()
slug?: string;
@IsOptional()
@IsString()
featuredImage?: string;
@IsOptional()
@IsArray()
@IsString({ each: true })
tags?: string[];
@IsOptional()
@IsEnum(ArticleStatus)
status?: ArticleStatus;
@IsOptional()
@IsString()
strapiId?: string;
@IsOptional()
@IsUUID()
authorId?: string;
@IsOptional()
@IsUUID()
categoryId?: string;
}
export class UpdateArticleDto {
@IsOptional()
@IsString()
title?: string;
@IsOptional()
@IsString()
content?: string;
@IsOptional()
@IsString()
excerpt?: string;
@IsOptional()
@IsString()
slug?: string;
@IsOptional()
@IsString()
featuredImage?: string;
@IsOptional()
@IsArray()
@IsString({ each: true })
tags?: string[];
@IsOptional()
@IsEnum(ArticleStatus)
status?: ArticleStatus;
@IsOptional()
@IsString()
strapiId?: string;
@IsOptional()
@IsUUID()
authorId?: string;
@IsOptional()
@IsUUID()
categoryId?: string;
}
export class FindArticlesDto {
@IsOptional()
@IsString()
category?: string;
@IsOptional()
@IsString()
author?: string;
@IsOptional()
@IsString()
tag?: string;
@IsOptional()
@IsEnum(ArticleStatus)
status?: ArticleStatus;
@IsOptional()
@IsString()
search?: string;
@IsOptional()
@IsNumber()
page?: number;
@IsOptional()
@IsNumber()
limit?: number;
}
+13
View File
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ArticlesService } from './articles.service';
import { ArticlesController } from './articles.controller';
import { Article, Author, Category } from './entities';
@Module({
imports: [TypeOrmModule.forFeature([Article, Author, Category])],
controllers: [ArticlesController],
providers: [ArticlesService],
exports: [ArticlesService],
})
export class ArticlesModule {}
+128
View File
@@ -0,0 +1,128 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Article, ArticleStatus } from './entities';
import {
CreateArticleDto,
UpdateArticleDto,
FindArticlesDto,
} from './articles.dto';
@Injectable()
export class ArticlesService {
constructor(
@InjectRepository(Article)
private readonly articleRepository: Repository<Article>,
) {}
async create(dto: CreateArticleDto): Promise<Article> {
const article = this.articleRepository.create({
...dto,
status: dto.status || ArticleStatus.DRAFT,
});
return await this.articleRepository.save(article);
}
async findAll(
dto: FindArticlesDto,
): Promise<{ data: Article[]; total: number }> {
const {
category,
author,
tag,
status = ArticleStatus.PUBLISHED,
search,
page = 1,
limit = 10,
} = dto;
const queryBuilder = this.articleRepository
.createQueryBuilder('article')
.leftJoinAndSelect('article.author', 'author')
.leftJoinAndSelect('article.category', 'category')
.where('article.status = :status', { status });
if (category) {
queryBuilder.andWhere('category.slug = :category', { category });
}
if (author) {
queryBuilder.andWhere('author.slug = :author', { author });
}
if (tag) {
queryBuilder.andWhere(':tag = ANY(article.tags)', { tag });
}
if (search) {
queryBuilder.andWhere(
'(article.title ILIKE :search OR article.content ILIKE :search)',
{ search: `%${search}%` },
);
}
const [data, total] = await queryBuilder
.orderBy('article.createdAt', 'DESC')
.skip((page - 1) * limit)
.take(limit)
.getManyAndCount();
return { data, total };
}
async findOne(id: string): Promise<Article> {
const article = await this.articleRepository.findOne({
where: { id },
relations: ['author', 'category'],
});
if (!article) {
throw new NotFoundException(`Article with ID ${id} not found`);
}
return article;
}
async findBySlug(slug: string): Promise<Article> {
const article = await this.articleRepository.findOne({
where: { slug },
relations: ['author', 'category'],
});
if (!article) {
throw new NotFoundException(`Article with slug ${slug} not found`);
}
return article;
}
async update(id: string, dto: UpdateArticleDto): Promise<Article> {
const article = await this.findOne(id);
Object.assign(article, dto);
return await this.articleRepository.save(article);
}
async remove(id: string): Promise<void> {
const article = await this.findOne(id);
await this.articleRepository.remove(article);
}
async syncFromStrapi(
strapiId: string,
data: Partial<CreateArticleDto>,
): Promise<Article> {
let article = await this.articleRepository.findOne({ where: { strapiId } });
if (!article) {
article = this.articleRepository.create({
strapiId,
...data,
status: data.status || ArticleStatus.DRAFT,
});
} else {
Object.assign(article, data);
}
return await this.articleRepository.save(article);
}
}
+129
View File
@@ -0,0 +1,129 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
export enum ArticleStatus {
DRAFT = 'draft',
PUBLISHED = 'published',
ARCHIVED = 'archived',
}
@Entity('authors')
export class Author {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column({ unique: true })
slug: string;
@Column({ nullable: true })
bio: string;
@Column({ nullable: true })
avatar: string;
@Column({ default: false })
isActive: boolean;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
@Entity('categories')
export class Category {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column({ unique: true })
slug: string;
@Column({ nullable: true })
description: string;
@Column({ nullable: true })
parentId: string;
@Column({ default: 0 })
order: number;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@ManyToOne(() => Category, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'parentId' })
parent: Category;
}
@Entity('articles')
export class Article {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
title: string;
@Column('text')
content: string;
@Column({ type: 'text', nullable: true })
excerpt: string;
@Column({ default: '' })
slug: string;
@Column({ default: '' })
featuredImage: string;
@Column({ type: 'text', default: '[]' })
tags: string[];
@Column({
type: 'text',
default: 'draft',
})
status: ArticleStatus;
@Column({ default: 0 })
views: number;
@Column({ nullable: true })
strapiId: string;
@Column({ nullable: true })
authorId: string;
@Column({ nullable: true })
categoryId: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@ManyToOne(() => Author, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'authorId' })
author: Author;
@ManyToOne(() => Category, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'categoryId' })
category: Category;
}
+33
View File
@@ -0,0 +1,33 @@
import { Controller, Post, Body } from '@nestjs/common';
import { StrapiService } from './strapi.service';
interface WebhookBody {
event: 'entry.create' | 'entry.update' | 'entry.delete';
model: string;
entry: {
documentId: string;
};
}
@Controller('webhooks/strapi')
export class StrapiController {
constructor(private readonly strapiService: StrapiService) {}
@Post('article')
async handleArticleWebhook(@Body() body: WebhookBody) {
const { event, model, entry } = body;
if (model !== 'article') {
return { message: 'Ignored: not an article' };
}
await this.strapiService.handleWebhook(event, entry);
return { message: 'Webhook processed successfully' };
}
@Post('sync/all')
async syncAllArticles() {
await this.strapiService.syncArticles();
return { message: 'Sync completed' };
}
}
+13
View File
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';
import { StrapiService } from './strapi.service';
import { StrapiController } from './strapi.controller';
import { ArticlesModule } from './articles.module';
@Module({
imports: [HttpModule, ArticlesModule],
controllers: [StrapiController],
providers: [StrapiService],
exports: [StrapiService],
})
export class StrapiModule {}
+156
View File
@@ -0,0 +1,156 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { HttpService } from '@nestjs/axios';
import { lastValueFrom } from 'rxjs';
import { ArticlesService } from './articles.service';
import { CreateArticleDto } from './articles.dto';
import { ArticleStatus } from './entities';
interface StrapiArticle {
id: number;
documentId: string;
title: string;
description: string;
content: string;
slug: string;
publishedAt: string | null;
createdAt: string;
updatedAt: string;
}
interface StrapiResponse<T> {
data: T;
meta: {
pagination: {
page: number;
pageSize: number;
pageCount: number;
total: number;
};
};
}
@Injectable()
export class StrapiService {
private readonly logger = new Logger(StrapiService.name);
private readonly strapiUrl: string;
private readonly strapiApiToken: string;
constructor(
private readonly configService: ConfigService,
private readonly httpService: HttpService,
private readonly articlesService: ArticlesService,
) {
this.strapiUrl =
this.configService.get<string>('STRAPI_URL') || 'http://localhost:1337';
this.strapiApiToken =
this.configService.get<string>('STRAPI_API_TOKEN') || '';
}
private getHeaders() {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};
if (this.strapiApiToken) {
headers['Authorization'] = `Bearer ${this.strapiApiToken}`;
}
return headers;
}
async syncArticles(): Promise<void> {
try {
this.logger.log('Starting articles sync from Strapi...');
const response = await lastValueFrom(
this.httpService.get<StrapiResponse<StrapiArticle[]>>(
`${this.strapiUrl}/api/articles`,
{
headers: this.getHeaders(),
},
),
);
const strapiArticles = response.data.data;
let syncedCount = 0;
for (const strapiArticle of strapiArticles) {
const articleData: Partial<CreateArticleDto> = {
title: strapiArticle.title,
excerpt: strapiArticle.description,
content: strapiArticle.content,
slug: strapiArticle.slug,
status: strapiArticle.publishedAt
? ArticleStatus.PUBLISHED
: ArticleStatus.DRAFT,
tags: [],
};
await this.articlesService.syncFromStrapi(
strapiArticle.documentId,
articleData,
);
syncedCount++;
}
this.logger.log(
`Successfully synced ${syncedCount} articles from Strapi`,
);
} catch (error) {
this.logger.error('Failed to sync articles from Strapi', error);
throw error;
}
}
async syncSingleArticle(strapiId: string): Promise<void> {
try {
this.logger.log(`Syncing single article from Strapi: ${strapiId}`);
const response = await lastValueFrom(
this.httpService.get<StrapiResponse<StrapiArticle>>(
`${this.strapiUrl}/api/articles/${strapiId}`,
{
headers: this.getHeaders(),
},
),
);
const strapiArticle = response.data.data;
const articleData: Partial<CreateArticleDto> = {
title: strapiArticle.title,
excerpt: strapiArticle.description,
content: strapiArticle.content,
slug: strapiArticle.slug,
status: strapiArticle.publishedAt
? ArticleStatus.PUBLISHED
: ArticleStatus.DRAFT,
tags: [],
};
await this.articlesService.syncFromStrapi(
strapiArticle.documentId,
articleData,
);
this.logger.log(`Successfully synced article: ${strapiArticle.title}`);
} catch (error) {
this.logger.error(
`Failed to sync article ${strapiId} from Strapi`,
error,
);
throw error;
}
}
async handleWebhook(
event: 'entry.create' | 'entry.update' | 'entry.delete',
data: { documentId: string },
): Promise<void> {
this.logger.log(`Received webhook event: ${event}`);
if (event === 'entry.delete') {
this.logger.log(`Handling delete for document: ${data.documentId}`);
return;
}
await this.syncSingleArticle(data.documentId);
}
}